S
shangxuan
Unregistered / Unconfirmed
GUEST, unregistred user!
procedure TForm1.Button2Click(Sender: TObject);<br>var<br> hNewCommFile,hCommFile: THandle;<br> commtimeouts: TCommTimeouts;<br> dcb: Tdcb;<br> commprop: TCommProp;<br> fdwEvtMask: DWORD;<br> pDataToWrite: PChar;<br> dwNumberOfBytesWritten,dwNumberOfBytesToWriteword;<br> lpOverlappedWrite: POverlapped;<br>begin<br> hNewCommFile := CreateFile( 'com1',<br> GENERIC_READ or GENERIC_WRITE,<br> 0,<br> nil,<br> OPEN_EXISTING,<br> FILE_ATTRIBUTE_NORMAL or FILE_FLAG_OVERLAPPED,<br> 0 <br><br> if hNewCommFile = INVALID_HANDLE_VALUE then<br> raise ECommsError.Create( 'Error opening serial port' );<br><br> // Is this a valid comm handle?<br> if GetFileType( hNewCommFile ) <> FILE_TYPE_CHAR then<br> begin<br> CloseHandle( hNewCommFile );<br> raise ECommsError.Create( 'File handle is not a comm handle ' )<br> end;<br><br> if not SetupComm( hNewCommFile, 4096, 4096 ) then<br> begin<br> CloseHandle( hNewCommFile );<br> raise ECommsError.Create( 'Cannot setup comm buffer' )<br> end;<br> // purge any information in the buffer<br><br> PurgeComm( hNewCommFile, PURGE_TXABORT or PURGE_RXABORT or<br> PURGE_TXCLEAR or PURGE_RXCLEAR ) ;<br><br><br><br> GetCommTimeouts( hNewCommFile, commtimeouts );<br><br> // The CommTimeout numbers will very likely change if you are<br> // coding to meet some kind of specification where<br> // you need to reply within a certain amount of time after<br> // recieving the last byte. However, If 1/4th of a second<br> // goes by between recieving two characters, its a good<br> // indication that the transmitting end has finished, even<br> // assuming a 1200 baud modem.<br><br> commtimeouts.ReadIntervalTimeout := 100;<br> commtimeouts.ReadTotalTimeoutMultiplier := 0;<br> commtimeouts.ReadTotalTimeoutConstant := 0;<br> commtimeouts.WriteTotalTimeoutMultiplier := 0;<br> commtimeouts.WriteTotalTimeoutConstant := 0;<br><br> SetCommTimeouts( hNewCommFile, commtimeouts );<br><br> GetCommState( hNewCommFile, dcb );<br> GetCommProperties(hNewCommFile, commprop );<br> GetCommMask(hNewCommFile, fdwEvtMask );<br> dcb.BaudRate := 9600;<br> dcb.Flags := 1;<br> dcb.Parity :=NOPARITY;<br> Dcb.ByteSize :=8;<br> dcb.StopBits :=ONESTOPBIT;<br> SetCommMask(hNewCommFile,EV_ERR or EV_RXCHAR);<br> SetCommState(hNewCommFile,Dcb);<br> hCommFile:=hNewCommFile;<br><br><br> pDataToWrite:='dsfasf';<br> dwNumberOfBytesToWrite:=strlen(pDataToWrite);<br> dwNumberOfBytesWritten:=5;<br> //出现错误,查询到的错误是error handle;<br> if not WriteFile(hCommFile,<br> pDataToWrite,<br> dwNumberOfBytesToWrite, dwNumberOfBytesWritten,<br> lpOverlappedWrite ) then<br> showMessage(inttostr(getlasterror()));<br>//下面我要查询事件有数据收到<br>//然后再读串口<br>//然后再写串口......<br><br>end;<br>