原文来自:http://bbs.csdn.net/topics/390359398?page=1#post-395222951
最近在写串口的程序,上网查了一些文章,都大同小异。按照作者的代码,写了一个串口异步操作的程序,带总是不对,总是遇到句柄无效或参数错误的问题。上论坛发现有这问题的人不少,但都没有解决办法。最后无奈之下,上MSDN查了文档,终于解决了问题,现在拿出来跟大家分享。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
char
buffer[1024];
DWORD
dwBytesWritten=1024;
DWORD
dwErrorFlags;
COMSTAT ComStat;
OVERLAPPED m_osWrite;
BOOL
bWriteStat;
bWriteStat = WriteFile(hCom,buffer, dwBytesWritten, &dwBytesWritten, &m_OsWrite);
if
(!bWriteStat)
{
if
(GetLastError()==ERROR_IO_PENDING)
{
WaitForSingleObject(m_osWrite.hEvent,1000);
return
dwBytesWritten;
}
return
0;
}
return
dwBytesWritten;
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
char
buffer[1024];
DWORD
dwBytesWritten=1024;
DWORD
dwErrorFlags;
COMSTAT ComStat;
OVERLAPPED m_osWrite;
BOOL
bWriteStat;
//初始化overlaooped结构!!
m_osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
m_osWrite.Offset = 0;
m_osWrite.OffsetHigh = 0;
bWriteStat = WriteFile(hCom,buffer, dwBytesWritten, &dwBytesWritten, &m_OsWrite);
if
(!bWriteStat)
{
if
(GetLastError()==ERROR_IO_PENDING)
{
WaitForSingleObject(m_osWrite.hEvent,1000);
return
dwBytesWritten;
}
return
0;
}
return
dwBytesWritten;
|