Window s 串口编程API 函数 发表时间:2010-12-26 点击数:1232 ·打开串口: HANDLE CreateFile( LPCTSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile ); 在Windows CE 下,利用CreateFile 函数打开一个COM 口时,dwShareMode(共享模式)必须设置为0,表示独占方式;lpSecurityAttributes(安全参数)必须设置为NULL;hTemplateFile(模板文件)必须设置为NULL;dwCreationDisposition 需要设置为OPEN_EXISTING。则上述函数简化为: HANDLE CreateFile( LPCTSTR lpFileName, DWORD dw DesiredAccess, 0, NULL, OPEN_EXISTING, DWORD dw FlagsAndAttributes, NULL ); 其中 dwDesiredAccess 设置为GENERIC_READ 表示可读,设置为GENERIC_WRITE 表示可写。通常可通过如下示例打开一个串口。 CreateFile( _T("COM1:"), GENERIC_READ | GENERIC_WRITE, //允许读和写 0, //独占方式(共享模式) NULL, OPEN_EXISTING, //打开而不是创建(创建方式) 0, NULL ); 打开串口成功,函数返回串口句柄;打开串口失败,函数返回INVALID_HANDLE_VALUE ·关闭串口: BOOL CloseHandle( HANDLE hObject ); 如:CloseHandle(m_hComm); //m_hComm 是CreateFile 函数返回的串口句柄。 关闭串口成功,函数返回非零值;关闭串口失败,函数返回零。 ·DCB(设备控制块): DCB 结构完全描述了串口的使用参数。 typedef struct _DCB { DWORD DCBlength; /* sizeof(DCB) */ DWORD BaudRate; /* Baudrate at which running */ DWORD fBinary: 1; /* Binary Mode (skip EOF check) */ DWORD fParity: 1; /* Enable parity checking */ DWORD fOutxCtsFlow:1; /* CTS handshaking on output */ DWORD fOutxDsrFlow:1; /* DSR handshaking on output */ DWORD fDtrControl:2; /* DTR Flow control */ DWORD fDsrSensitivity:1; /* DSR Sensitivity */ DWORD fTXContinueOnXoff: 1; /* Continue TX when Xoff sent */ DWORD fOutX: 1; /* Enable output X-ON/X-OFF */ DWORD fInX: 1; /* Enable input X-ON/X-OFF */ DWORD fErrorChar: 1; /* Enabl...