{
string baudRate;
Console.Write(\, defaultPortBaudRate);
baudRate = Console.ReadLine();
if (baudRate == \) {
baudRate = defaultPortBaudRate.ToString(); }
return int.Parse(baudRate); }
public static Parity SetPortParity(Parity defaultPortParity) {
string parity;
Console.WriteLine(\options:\);
foreach (string s in Enum.GetNames(typeof(Parity))) {
Console.WriteLine(\, s); }
Console.Write(\, defaultPortParity.ToString());
parity = Console.ReadLine();
if (parity == \) {
parity = defaultPortParity.ToString(); }
return (Parity)Enum.Parse(typeof(Parity), parity); }
public static int SetPortDataBits(int defaultPortDataBits) {
string dataBits;
Console.Write(\, defaultPortDataBits);
dataBits = Console.ReadLine();
if (dataBits == \) {
dataBits = defaultPortDataBits.ToString(); }
return int.Parse(dataBits);
}
public static StopBits SetPortStopBits(StopBits defaultPortStopBits) {
string stopBits;
Console.WriteLine(\options:\);
foreach (string s in Enum.GetNames(typeof(StopBits))) {
Console.WriteLine(\, s); }
Console.Write(\, defaultPortStopBits.ToString());
stopBits = Console.ReadLine();
if (stopBits == \) {
stopBits = defaultPortStopBits.ToString(); }
return (StopBits)Enum.Parse(typeof(StopBits), stopBits); }
public static Handshake SetPortHandshake(Handshake defaultPortHandshake) {
string handshake;
Console.WriteLine(\options:\);
foreach (string s in Enum.GetNames(typeof(Handshake))) {
Console.WriteLine(\, s); }
Console.Write(\, defaultPortHandshake.ToString());
handshake = Console.ReadLine();
if (handshake == \) {
handshake = defaultPortHandshake.ToString(); }
return
(Handshake)Enum.Parse(typeof(Handshake), handshake); } }
SerialPort类的源代码已经放在下面,SerialPort类是由Remon Spekreijse提供的免费串口类。 CSerialPort支持线连接的串口编程,而且是基于多线程的,工作流程:
1.设置串口参数。 函数原型:
BOOL CSerialPort::InitPort(CWnd* pPortOwner, // the owner (CWnd) of the port (receives message) UINT portnr, // portnumber (1..4) UINT baud, // baudrate char parity, // parity UINT databits, // databits UINT stopbits, // stopbits DWORD dwCommEvents, // EV_RXCHAR, EV_CTS etc UINT writebuffersize) // size to the writebuffer
2.串口监测线程。
BOOL CSerialPort::StartMonitoring() BOOL CSerialPort::RestartMonitoring() BOOL CSerialPort::StopMonitoring() void CSerialPort::WriteChar(CSerialPort* port) void CSerialPort::ReceiveChar(CSerialPort* port, COMSTAT comstat) void CSerialPort::WriteToPort(char* string) 3.监测线程接收事件信息,再进行消息处理即可。 SerialPort类的应用
基于对话框的串口程序开发:
1.将SerialPort类添加进工程; 2.进行消息的映射;
(注意:在SerialPort类的头文件中的:
#define WM_COMM_RXCHAR WM_USER+7 需要手动进行映射)