我参照例子, 用CREATEFILE取的COM1的HANDLE, 然后设置其配置, 最后, 用READFILE来获取COM1的数据, 但是, 每次一到READFILE, 就会报 INVALID HANDLE的错误.
大致代码:
//取得COM1的HANDLE
HANDLE m_Port = CreateFile("COM1:",GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL);
if (m_Port == INVALID_HANDLE_VALUE){
// Handle the error.
return false ;
}
// 配置COM1
DCB dcb;
if (!GetCommState(m_Port, &dcb)){
return false;
}
dcb.BaudRate = CBR_9600; // set the baud rate
dcb.ByteSize = 8; // data size, xmit, and rcv
dcb.Parity = NOPARITY; // no parity bit
dcb.StopBits = ONESTOPBIT; // one stop bit
if (!SetCommState(m_Port, &dcb)){
return false;
}
//读取数据
char input[200];
unsigned int lenBuff = 200;
LPDWORD lenMessage;
String *strResult;
if(ReadFile(m_Port,input,lenBuff,lenMessage,NULL)==0){ //这里会有EXCEPTION
return false;
}
大致代码:
//取得COM1的HANDLE
HANDLE m_Port = CreateFile("COM1:",GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL);
if (m_Port == INVALID_HANDLE_VALUE){
// Handle the error.
return false ;
}
// 配置COM1
DCB dcb;
if (!GetCommState(m_Port, &dcb)){
return false;
}
dcb.BaudRate = CBR_9600; // set the baud rate
dcb.ByteSize = 8; // data size, xmit, and rcv
dcb.Parity = NOPARITY; // no parity bit
dcb.StopBits = ONESTOPBIT; // one stop bit
if (!SetCommState(m_Port, &dcb)){
return false;
}
//读取数据
char input[200];
unsigned int lenBuff = 200;
LPDWORD lenMessage;
String *strResult;
if(ReadFile(m_Port,input,lenBuff,lenMessage,NULL)==0){ //这里会有EXCEPTION
return false;
}