轉載地址:http://huxud.blog.sohu.com/5702440.htmlhtml
學了C#,由於本人搞嵌入式方面的研究,不免和串口多有打交道,故用c#作了個串口發送應用程序。由於.net2003尚未作串口控件進去,因此這個程序化了我1個星期,包括類的處理以及不少次的調試,如今已經能夠實現串口的打開併發送數據(關閉和接收沒作好,時間問題:)),仍是等下.net2005再弄了(聽說2005把串口控件作進去了,方便了呀!)windows
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;api
namespace SerialPort_628
{
/// <summary>
/// Form1 的摘要說明。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.TextBox textBox4;
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.TextBox SendData;
private System.Windows.Forms.TextBox ReceiveData;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Timer timer1;
private System.Windows.Forms.PictureBox pictureBox2;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.ComboBox comboBox2;
private System.ComponentModel.IContainer components;安全
public Form1()
{
//
// Windows 窗體設計器支持所必需的
//
InitializeComponent();併發
//
// TODO: 在 InitializeComponent 調用後添加任何構造函數代碼
//
}app
/// <summary>
/// 清理全部正在使用的資源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}異步
#region Windows 窗體設計器生成的代碼
/// <summary>
/// 設計器支持所需的方法 - 不要使用代碼編輯器修改
/// 此方法的內容。
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.SendData = new System.Windows.Forms.TextBox();
this.ReceiveData = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.textBox2 = new System.Windows.Forms.TextBox();
this.textBox4 = new System.Windows.Forms.TextBox();
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.button2 = new System.Windows.Forms.Button();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.pictureBox2 = new System.Windows.Forms.PictureBox();
this.button3 = new System.Windows.Forms.Button();
this.comboBox2 = new System.Windows.Forms.ComboBox();
this.SuspendLayout();
//
// SendData
//
this.SendData.Location = new System.Drawing.Point(24, 96);
this.SendData.Multiline = true;
this.SendData.Name = "SendData";
this.SendData.Size = new System.Drawing.Size(176, 184);
this.SendData.TabIndex = 0;
this.SendData.Text = "";
//
// ReceiveData
//
this.ReceiveData.Location = new System.Drawing.Point(488, 96);
this.ReceiveData.Multiline = true;
this.ReceiveData.Name = "ReceiveData";
this.ReceiveData.Size = new System.Drawing.Size(176, 184);
this.ReceiveData.TabIndex = 2;
this.ReceiveData.Text = "";
//
// button1
//
this.button1.Location = new System.Drawing.Point(296, 176);
this.button1.Name = "button1";
this.button1.TabIndex = 3;
this.button1.Text = "發送";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(24, 72);
this.textBox2.Name = "textBox2";
this.textBox2.ReadOnly = true;
this.textBox2.TabIndex = 4;
this.textBox2.Text = "發送數據區";
//
// textBox4
//
this.textBox4.Location = new System.Drawing.Point(488, 72);
this.textBox4.Name = "textBox4";
this.textBox4.ReadOnly = true;
this.textBox4.TabIndex = 5;
this.textBox4.Text = "接收數據區";
//
// comboBox1
//
this.comboBox1.Items.AddRange(new object[] {
"COM1 ",
"COM2"});
this.comboBox1.Location = new System.Drawing.Point(24, 32);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(64, 20);
this.comboBox1.TabIndex = 6;
this.comboBox1.Text = "COM1 ";
this.comboBox1.TextChanged += new System.EventHandler(this.comboBox1_TextChanged);
//
// button2
//
this.button2.Location = new System.Drawing.Point(128, 32);
this.button2.Name = "button2";
this.button2.TabIndex = 7;
this.button2.Text = "打開";
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// pictureBox1
//
this.pictureBox1.BackColor = System.Drawing.SystemColors.Control;
this.pictureBox1.Location = new System.Drawing.Point(104, 32);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(8, 16);
this.pictureBox1.TabIndex = 8;
this.pictureBox1.TabStop = false;
//
// timer1
//
this.timer1.Interval = 1000;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// pictureBox2
//
this.pictureBox2.BackColor = System.Drawing.SystemColors.Control;
this.pictureBox2.Location = new System.Drawing.Point(568, 40);
this.pictureBox2.Name = "pictureBox2";
this.pictureBox2.Size = new System.Drawing.Size(8, 16);
this.pictureBox2.TabIndex = 11;
this.pictureBox2.TabStop = false;
//
// button3
//
this.button3.Location = new System.Drawing.Point(592, 40);
this.button3.Name = "button3";
this.button3.TabIndex = 10;
this.button3.Text = "打開";
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// comboBox2
//
this.comboBox2.Items.AddRange(new object[] {
"COM1 ",
"COM2"});
this.comboBox2.Location = new System.Drawing.Point(488, 40);
this.comboBox2.Name = "comboBox2";
this.comboBox2.Size = new System.Drawing.Size(64, 20);
this.comboBox2.TabIndex = 9;
this.comboBox2.Text = "COM2";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(696, 346);
this.Controls.Add(this.pictureBox2);
this.Controls.Add(this.button3);
this.Controls.Add(this.comboBox2);
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.button2);
this.Controls.Add(this.comboBox1);
this.Controls.Add(this.textBox4);
this.Controls.Add(this.textBox2);
this.Controls.Add(this.button1);
this.Controls.Add(this.ReceiveData);
this.Controls.Add(this.SendData);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);編輯器
}
#endregionide
/// <summary>
/// 應用程序的主入口點。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
CommPort Sport = new CommPort();
CommPort Rport = new CommPort();
private void button1_Click(object sender, System.EventArgs e)
{
Sport.Write(System.Text.Encoding.Default.GetBytes(SendData.Text.ToString()));
//MessageBox.Show("數據已經發送!","",MessageBoxButtons.OK,MessageBoxIcon.Asterisk);
}函數
private void button2_Click(object sender, System.EventArgs e)
{
Sport.PortNum = comboBox1.Text.ToString(); //端口號
Sport.Parity = 0; //奇偶校驗
Sport.BaudRate = 9600;//串口通訊波特率
Sport.ByteSize = 8; //數據位
Sport.StopBits = 1;//中止位
Sport.ReadTimeout = 1000; //讀超時
if (Sport.Opened)
{
Sport.Close();
Sport.Open(); //打開串口
}
else
{
Sport.Open();//打開串口
}
pictureBox1.BackColor = System.Drawing.Color.Red;
}
private void comboBox1_TextChanged(object sender, System.EventArgs e)
{
pictureBox1.BackColor = System.Drawing.Color.WhiteSmoke;
}
private void timer1_Tick(object sender, System.EventArgs e)
{
if(Rport.Opened)
{
byte[] bs = Sport.Read(1);
ReceiveData.Text=System.Text.Encoding.ASCII.GetString(bs);
}
}
private void button3_Click(object sender, System.EventArgs e)
{
Rport.PortNum = comboBox2.Text.ToString(); //端口號
Rport.BaudRate = 9600;//串口通訊波特率
Rport.Parity = 0;//奇偶校驗
Rport.StopBits = 1;//中止位
Rport.ByteSize = 8;//數據位
Rport.ReadTimeout = 1000;//讀超時
if (Rport.Opened)
{
Rport.Close();
Rport.Open(); //打開串口
}
else
{
Rport.Open();//打開串口
}
pictureBox2.BackColor = System.Drawing.Color.Red;
}
}
class CommPort
{
public string PortNum;
public int BaudRate;
public byte ByteSize;
public byte Parity; // 0-4=no,odd,even,mark,space
public byte StopBits; // 0,1,2 = 1, 1.5, 2
public int ReadTimeout;
public bool Opened = false;
//win32 api constants
private const uint GENERIC_READ = 0x80000000;
private const uint GENERIC_WRITE = 0x40000000;
private const int OPEN_EXISTING = 3;
private const int INVALID_HANDLE_VALUE = -1;
//comm port win32 file handle
private int hComm = INVALID_HANDLE_VALUE;
[StructLayout(LayoutKind.Sequential)]
public struct DCB
{
//taken from c struct in platform sdk
public int DCBlength; // sizeof(DCB)
public int BaudRate; // 指定當前波特率 current baud rate
// these are the c struct bit fields, bit twiddle flag to set
public int fBinary; // 指定是否容許二進制模式,在windows95中必須主TRUE binary mode, no EOF check
public int fParity; // 指定是否容許奇偶校驗 enable parity checking
public int fOutxCtsFlow; // 指定CTS是否用於檢測發送控制,當爲TRUE是CTS爲OFF,發送將被掛起。 CTS output flow control
public int fOutxDsrFlow; // 指定CTS是否用於檢測發送控制 DSR output flow control
public int fDtrControl; // DTR_CONTROL_DISABLE值將DTR置爲OFF, DTR_CONTROL_ENABLE值將DTR置爲ON, DTR_CONTROL_HANDSHAKE容許DTR"握手" DTR flow control type
public int fDsrSensitivity; // 當該值爲TRUE時DSR爲OFF時接收的字節被忽略 DSR sensitivity
public int fTXContinueOnXoff; // 指定當接收緩衝區已滿,而且驅動程序已經發送出XoffChar字符時發送是否中止。TRUE時,在接收緩衝區接收到緩衝區已滿的字節XoffLim且驅動程序已經發送出XoffChar字符停止接收字節以後,發送繼續進行。 FALSE時,在接收緩衝區接收到表明緩衝區已空的字節XonChar且驅動程序已經發送出恢復發送的XonChar以後,發送繼續進行。XOFF continues Tx
public int fOutX; // TRUE時,接收到XoffChar以後便中止發送接收到XonChar以後將從新開始 XON/XOFF out flow control
public int fInX; // TRUE時,接收緩衝區接收到表明緩衝區滿的XoffLim以後,XoffChar發送出去接收緩衝區接收到表明緩衝區空的XonLim以後,XonChar發送出去 XON/XOFF in flow control
public int fErrorChar; // 該值爲TRUE且fParity爲TRUE時,用ErrorChar 成員指定的字符代替奇偶校驗錯誤的接收字符 enable error replacement
public int fNull; // eTRUE時,接收時去掉空(0值)字節 enable null stripping
public int fRtsControl; // RTS flow control
public int fAbortOnError; // TRUE時,有錯誤發生時停止讀和寫操做 abort on error
public int fDummy2; // 未使用 reserved
public uint flags;
public ushort wReserved; // 未使用,必須爲0 not currently used
public ushort XonLim; // 指定在XON字符發送這前接收緩衝區中可容許的最小字節數 transmit XON threshold
public ushort XoffLim; // 指定在XOFF字符發送這前接收緩衝區中可容許的最小字節數 transmit XOFF threshold
public byte ByteSize; // 指定端口當前使用的數據位 number of bits/byte, 4-8
public byte Parity; // 指定端口當前使用的奇偶校驗方法,可能爲:EVENPARITY,MARKPARITY,NOPARITY,ODDPARITY 0-4=no,odd,even,mark,space
public byte StopBits; // 指定端口當前使用的中止位數,可能爲:ONESTOPBIT,ONE5STOPBITS,TWOSTOPBITS 0,1,2 = 1, 1.5, 2
public char XonChar; // 指定用於發送和接收字符XON的值 Tx and Rx XON character
public char XoffChar; // 指定用於發送和接收字符XOFF值 Tx and Rx XOFF character
public char ErrorChar; // 本字符用來代替接收到的奇偶校驗發生錯誤時的值 error replacement character
public char EofChar; // 當沒有使用二進制模式時,本字符可用來指示數據的結束 end of input character
public char EvtChar; // 當接收到此字符時,會產生一個事件 received event character
public ushort wReserved1; // 未使用 reserved; do not use
}
[StructLayout(LayoutKind.Sequential)]
private struct COMMTIMEOUTS
{
public int ReadIntervalTimeout;
public int ReadTotalTimeoutMultiplier;
public int ReadTotalTimeoutConstant;
public int WriteTotalTimeoutMultiplier;
public int WriteTotalTimeoutConstant;
}
[StructLayout(LayoutKind.Sequential)]
private struct OVERLAPPED
{
public int Internal;
public int InternalHigh;
public int Offset;
public int OffsetHigh;
public int hEvent;
}
[DllImport("kernel32.dll")]
private static extern int CreateFile(
string lpFileName, // 要打開的串口名稱
uint dwDesiredAccess, // 指定串口的訪問方式,通常設置爲可讀可寫方式
int dwShareMode, // 指定串口的共享模式,串口不能共享,因此設置爲0
int lpSecurityAttributes, // 設置串口的安全屬性,WIN9X下不支持,應設爲NULL
int dwCreationDisposition, // 對於串口通訊,建立方式只能爲OPEN_EXISTING
int dwFlagsAndAttributes, // 指定串口屬性與標誌,設置爲FILE_FLAG_OVERLAPPED(重疊I/O操做),指定串口以異步方式通訊
int hTemplateFile // 對於串口通訊必須設置爲NULL
);
[DllImport("kernel32.dll")]
private static extern bool GetCommState(
int hFile, //通訊設備句柄
ref DCB lpDCB // 設備控制塊DCB
);
[DllImport("kernel32.dll")]
private static extern bool BuildCommDCB(
string lpDef, // 設備控制字符串
ref DCB lpDCB // 設備控制塊
);
[DllImport("kernel32.dll")]
private static extern bool SetCommState(
int hFile, // 通訊設備句柄
ref DCB lpDCB // 設備控制塊
);
[DllImport("kernel32.dll")]
private static extern bool GetCommTimeouts(
int hFile, // 通訊設備句柄 handle to comm device
ref COMMTIMEOUTS lpCommTimeouts // 超時時間 time-out values
);
[DllImport("kernel32.dll")]
private static extern bool SetCommTimeouts(
int hFile, // 通訊設備句柄 handle to comm device
ref COMMTIMEOUTS lpCommTimeouts // 超時時間 time-out values
);
[DllImport("kernel32.dll")]
private static extern bool ReadFile(
int hFile, // 通訊設備句柄 handle to file
byte[] lpBuffer, // 數據緩衝區 data buffer
int nNumberOfBytesToRead, // 多少字節等待讀取 number of bytes to read
ref int lpNumberOfBytesRead, // 讀取多少字節 number of bytes read
ref OVERLAPPED lpOverlapped // 溢出緩衝區 overlapped buffer
);
[DllImport("kernel32.dll")]
private static extern bool WriteFile(
int hFile, // 通訊設備句柄 handle to file
byte[] lpBuffer, // 數據緩衝區 data buffer
int nNumberOfBytesToWrite, // 多少字節等待寫入 number of bytes to write
ref int lpNumberOfBytesWritten, // 已經寫入多少字節 number of bytes written
ref OVERLAPPED lpOverlapped // 溢出緩衝區 overlapped buffer
);
[DllImport("kernel32.dll")]
private static extern bool CloseHandle(
int hObject // handle to object
);
[DllImport("kernel32.dll")]
private static extern uint GetLastError();
public void Open()
{
DCB dcbCommPort = new DCB();
COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS();
// 打開串口 OPEN THE COMM PORT.
hComm = CreateFile(PortNum ,GENERIC_READ | GENERIC_WRITE,0, 0,OPEN_EXISTING,0,0);
// 若是串口沒有打開,就打開 IF THE PORT CANNOT BE OPENED, BAIL OUT.
if(hComm == INVALID_HANDLE_VALUE)
{
throw(new ApplicationException("串口被佔用,不能打開串口!"));
}
// 設置通訊超時時間 SET THE COMM TIMEOUTS.
GetCommTimeouts(hComm,ref ctoCommPort);
ctoCommPort.ReadIntervalTimeout = Int32.MaxValue;
ctoCommPort.ReadTotalTimeoutConstant = 0;
ctoCommPort.ReadTotalTimeoutMultiplier = 0;
ctoCommPort.WriteTotalTimeoutMultiplier = 10;
ctoCommPort.WriteTotalTimeoutConstant = 1000;
SetCommTimeouts(hComm,ref ctoCommPort);
// 設置串口 SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS.
dcbCommPort.DCBlength = Marshal.SizeOf(dcbCommPort);
GetCommState(hComm, ref dcbCommPort);
dcbCommPort.BaudRate=BaudRate;
dcbCommPort.Parity=Parity;
dcbCommPort.ByteSize=ByteSize;
dcbCommPort.StopBits=StopBits;
SetCommState(hComm, ref dcbCommPort);
Opened = true;
}
public void Close()
{
if (hComm!=INVALID_HANDLE_VALUE)
{
CloseHandle(hComm);
hComm = INVALID_HANDLE_VALUE;
Opened = false;
PortNum = null;
}
}
public byte[] Read(int NumBytes)
{
byte[] BufBytes;
byte[] OutBytes;
BufBytes = new byte[NumBytes];
if (hComm!=INVALID_HANDLE_VALUE)
{
OVERLAPPED ovlCommPort = new OVERLAPPED();
int BytesRead=0;
ReadFile(hComm,BufBytes,NumBytes,ref BytesRead,ref ovlCommPort);
OutBytes = new byte[BytesRead];
Array.Copy(BufBytes,OutBytes,BytesRead);
}
else
{
throw(new ApplicationException("串口未打開!"));
}
return OutBytes;
}
public void Write(byte[] WriteBytes)
{
if (hComm!=INVALID_HANDLE_VALUE)
{
OVERLAPPED ovlCommPort = new OVERLAPPED();
int BytesWritten = 0;
WriteFile(hComm,WriteBytes,WriteBytes.Length,ref BytesWritten,ref ovlCommPort);
}
else
{
throw(new ApplicationException("串口未打開!"));
}
}
}
}