原文来自: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;
|
没错,仅仅只是加了一段对OVERLAPPED结构的初始化!
句柄无效,不是由于串口的句柄造成,而是OVERLAPPED结构中的hEvent;
参数错误也是没有初始化Offset和OffsetHigh造成的。
这样才能正确的写串口,当然别忘了在后面加一句CloseHandle,同理可以应用到读串口上。希望对大家有所帮助!!