这是我的程序,请高手帮我看看:
void __fastcall COMM::Execute()
{
DWORD ERRORS, Counts;
COMSTAT commstat;
do
{
if(WaitCommEvent(hCom, &dwEvtMask, NULL) == TRUE)
{
if (dwEvtMask & EV_RXCHAR)
{
if(ClearCommError(hCom, &ERRORS, &commstat) == TRUE)
{
BYTE * Buffer = new BYTE [commstat.cbInQue];
if(ReadFile(hCom, Buffer, commstat.cbInQue, &Counts, NULL) == TRUE)
{
PostThreadMessage(commThread, WM_RXChar, Counts, (LPARAM)Buffer);
}
}
}
}
} while(1);
}
//---------------------------------------------------------------------------
BOOL __fastcall COMM::WriteToComm(int Length, BYTE * Buffer)
{
DWORD Counts;
BYTE * buffer = new BYTE [Length+3];
buffer[0] = '/xff', buffer[1] = '/xaa', buffer[2] = Length;
memcpy(buffer+3, Buffer, Length);
BOOL Result = WriteFile(hCom, buffer, Length+3, &Counts, NULL);
return Result;
}
//---------------------------------------------------------------------------
Boolean __fastcall COMM::InitComm(char * portSel, int baudRate, int byteSize, int parity, int stopBits)
{
if(hCom) {
PurgeComm(hCom, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|PURGE_RXCLEAR);
CloseHandle(hCom);
}
hCom = CreateFile(portSel,
GENERIC_READ | GENERIC_WRITE,
0, /* exclusive access */
NULL, /* no security attrs */
OPEN_EXISTING,
0,//FILE_FLAG_OVERLAPPED,
NULL
);
if (hCom == INVALID_HANDLE_VALUE){
MessageBox(NULL, "不能打开通信端口", "打开错误", MB_OK|MB_ICONERROR);
return False;
}
DCB dcb;
BOOL fSuccess;
int BaudRate[4] = { 9600, 4800, 2400, 1200 };
GetCommState(hCom, &dcb);
dcb.BaudRate = BaudRate[baudRate];
dcb.ByteSize = 4+byteSize;
dcb.Parity = parity;
dcb.StopBits = stopBits;
fSuccess = SetCommState(hCom, &dcb);
fSuccess = SetCommMask(hCom, EV_RXCHAR);
PurgeComm(hCom, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|PURGE_RXCLEAR);
char Parity[3] = "NOE";
char StopBits[3][4] = { "1", "1.5", "2" };
fmMain->sbText->Panels->Items[1]->Text =
AnsiString(int(dcb.BaudRate))+'-'+AnsiString(int(dcb.ByteSize))+'-'
+Parity[parity]+'-'+StopBits[stopBits];
return True;
}