Unit unit1;
Interface
Uses Windows, Messages, Sysutils, Classes, Graphics, Controls, Forms, Dialogs, Stdctrls, ExtCtrls
type TForm1 = class (TForm) rdCOM: TRadioGroup; Label1: TLabel; mSend: TMemo; Label2: TLabel; mReceive: TMemo; btnOpenPort: TButton; btnSend: TButton; btnEnd: TButton; Timer1: TTimer; procedure btnSendClick (Sender: TObject) ; procedure btnOpenPortClick (Sender: TObject); procedure btnEndClick (Sender: TObject); procedure Timer1Timer (Sender: TObject); procedure mSendKeyPress (Sender: TObject; var Key: Char); private {Private declarations} public {public declarations} procedure OpenComm ; // Open the communication port end;
Var Form1: TFORM1; HCOMM: THANDLE;
IMPLEMentation
{$ R * .dfm}
Procedure tform1.btnsendclick (sender: Tobject); var temp: string; lrc: longword; begin if (hcomm = 0) THEN EXIT; TEMP: = msend.text; Writefile (hcomm, pointer (temp) ^, Length (TEMP) , LRC, NIL); // Delivered Data End;
Procedure TFORM1.BTNOPENPORTCLICK (Sender: TOBJECT);
Begin // If the communication port has been opened, no need to turn the IF (hcomm <> 0) The beginning ('communication port is opened! No need to open!'); exit; end; opencomm; end;
// The following is a program procedure tform1.opencommmmmmmmmmmmmmmmmmmmmm; TEMP: Tcommconfig; Temp: string; begin Temp: = 'COM' INTOSTR (RDcom.ItemIndex 1); // Select the COM hcomm: = Createfile (Pchar (Temp), Generic_read or Generic_Write, 0, NIL, Open_EXISTING, 0, 0); // Open COM if (hcomm = invalid_handle_value) THEN BEGIN / / If COM does not open MessageBox (0, 'open communication port errors! ! ',' ', Mb_ok; exit;
Getcommstate (hcomm, cc.dcb); // Know the status cc.dcb.baudrate: = CBR_9600; // set the baud rate is 9600 cc.dcb.bytesize: = 8; // byte is 8 bit cc.dcb.parity: = noparity; // Parity is none cc.dcb.stopbits: = onestopbit; // 1 stop bitif note setcommstate (hcomm, cc.dcb) THEN BEGIN / / Status MessageBox (0, 'Communication port setting error !!!', '', mb_ok); CloseHandle (hcomm); exit; end;
Procedure TFORM1.BTNENDCLICK (Sender: Tobject); Begin CloseHandle (HCOMM); // Turn off Communication Port Close; // End Program End;
// timer event procedure tform1.timer1timer (sender: Tobject); var temp: string; inbuff: array [0.2047] of char; nbytesread, dwerror: longword; cs: tcomstat; begin clearcommorror (hcomm, dwerror, @ CS); // Get the status if cs.cbinque = 0 THEN EXIT; if cs.cbinque> Sizeof (Inbuff) THEN BEGIN PURGECMMMMMMMMM (h 清); // Clear COM Data EXIT; End; ReadFile (hcomm, inbuff, Cs.cbinque, nbytesread, nil); // Receive the data of COM Temp: = COPY (Inbuff, 1, cs.cbinque); MRECEVE.TEXT: = MRECEIVE.TEXT TEMP; // Display data on MEMO1 on MRECEIVE .SetFocus; MRECEIVE.SELSTART: = Length (MRECEIVE.TEXT); MRECEIVE.SELLENGTH: = 0; // Move MEMO's display position to the lowermost end END; // The following is the processing button action procedure TFORM1.MSENDKEYPRESS (Sender: Tobject Var key: char); begin if key = # 13 damsendclick (sender);
End.