我試圖用C++編寫一個串行端口與WIN32 API,WriteFile不會返回ERROR_IO_PENDING,但沒有任何反應,但是在我寫使用其他程序的端口(C#)的C++程序的工作,直到我重新啓動windows 7,這裏是寫代碼:使用win32 API寫入串行端口 - 端口將不會打開,直到我打開它其他地方
static DCB dcb = {0};
static HANDLE hComm;
static int _tmain(int argc, _TCHAR* argv[])
{
hComm = CreateFile(
L"\\\\.\\COM3",
GENERIC_WRITE | GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
NULL,
NULL
);
if (hComm == INVALID_HANDLE_VALUE) // error opening port; abort
printf_s("INVALID_HANDLE_VALUE\n");
if (GetCommState(hComm, &dcb))// DCB is ready for use.
{
dcb.BaudRate = CBR_19200; //19200 Baud
dcb.ByteSize = 8; //8 data bits
dcb.Parity = NOPARITY; //no parity
dcb.StopBits = ONESTOPBIT; //1 stop
printf_s("set UP DCB\n");
}
else // Error getting current DCB settings
printf_s("ERROR getting \n"+GetLastError());
osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
WriteABuffer("!serialCMDtoSend\r",sizeof("!serialCMDtoSend\r");
}
static BOOL WriteABuffer(char * lpBuf, DWORD dwToWrite)
{
// Issue write.
if (!WriteFile(hComm, lpBuf, dwToWrite, &dwWritten, &osWrite))
{
if (GetLastError() != ERROR_IO_PENDING) { // WriteFile failed, but it isn't delayed. Report error and abort.
fRes = FALSE;
}
else {
// Write is pending.
if (!GetOverlappedResult(hComm, &osWrite, &dwWritten, TRUE))
fRes = FALSE;
else
fRes = TRUE;// Write operation completed successfully.
}
}
else
fRes = TRUE; // WriteFile completed immediately.
return fRes;
}
有誰能夠看到我的錯誤?
,我試圖faloow的示例是從MSDN: http://msdn.microsoft.com/en-us/library/ff802693.aspx 那裏它們復位DCB這樣的: DCB DCB = {0} ; – user1120007
@ user1120007:我報告過文檔錯誤。調用'GetCommState'之前需要設置'DCBlength'成員。這對於接受結構的Win32 API非常常見,因爲結構大小可以在Windows版本之間改變,所以您需要告訴Windows Windows程序使用的結構的大小(版本)。 (否則將沒有理由在結構中有所有尺寸) –