vc读写rs232口

打开RS232:
HANDLE hComPort = CreateFile(
"COM1", //String,COM name. GENERIC_READ|GENERIC_WRITE, // access mode
0, // share mode
NULL, // security attributes
OPEN_EXISTING, // how to create
FILE_FLAG_OVERLAPPED,// file attributes
NULL); // handle to file with attributes to copy

if (hComPort == INVALID_HANDLE_VALUE)
return FALSE;

if (!GetCommState(hComPort, &dcb))
{
CloseHandle(hComPort);
return FALSE;
}
//设置通信参数
dcb.BaudRate = (DWORD)m_SysOption.nBaudRateModem;
dcb.ByteSize = (BYTE)m_SysOption.nByteSizeModem;
dcb.StopBits = (BYTE)m_SysOption.nStopBitsModem;
dcb.Parity = (BYTE)m_SysOption.nParityModem;
dcb.EvtChar = COMM_TAILOR;
dcb.fDtrControl = DTR_CONTROL_ENABLE;

if(!SetCommState(hComPort, &dcb))
{
CloseHandle(hComPort);
return FALSE;
}

if (!SetCommMask(hComPort, EV_RXFLAG))
{
CloseHandle(hComPort);
return FALSE;
}

//set com timeout
COMMTIMEOUTS CommTimeOuts;
CommTimeOuts.ReadIntervalTimeout = MAXDWORD;
CommTimeOuts.ReadTotalTimeoutMultiplier = 0;
CommTimeOuts.ReadTotalTimeoutConstant = 0;
CommTimeOuts.WriteTotalTimeoutMultiplier = 0;
CommTimeOuts.WriteTotalTimeoutConstant = 0;
if (!SetCommTimeouts(hComPort,&CommTimeOuts))
{
CloseHandle(hComPort);
return FALSE;
}

if (!PurgeComm(hComPort, PURGE_TXCLEAR|PURGE_RXCLEAR))
{
CloseHandle(hComPort);
return FALSE;
}

读取:
OVERLAPPED OVL;
memset(&OVL,0,sizeof(OVERLAPPED));
OVL.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
ReadFile(hComPort ,pBufRecv,dwToRead,&dwLen,&OVL)
输出:
OVERLAPPED OVL;
memset(&OVL,0,sizeof(OVERLAPPED));
OVL.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
ReadFile(hComPort ,pBufRecv,dwToRead,&dwLen,&OVL)

WriteFile(hComPort ,pBufSend,dwLen,& dwLen, &OVL);//WIN98下,&OVL可以为NULL
//在NT或WIN2K下不能为NULL


你可能感兴趣的:(Security,Access,vc++)