Показать сообщение отдельно
  #10  
Старый 21.05.2018, 12:24
Аватар для Alegun
Alegun Alegun вне форума
LMD-DML
 
Регистрация: 12.07.2009
Адрес: Богородское
Сообщения: 3,025
Версия Delphi: D7E
Репутация: 1834
По умолчанию

Тогда вам видимо вот это пригодится
Код:
interface
uses Windows;

type
TComPort = class
private
   hFile: THandle;
public
   constructor Create;
   destructor Destroy; override;
   function InitCom(BaudRate, PortNo: Integer; Parity: Char;
     CommTimeOuts: TCommTimeouts): Boolean;
   procedure CloseCom;
   function ReceiveCom(var Buffer; Size: DWORD): Integer;
   function SendCom(var Buffer; Size: DWORD): Integer;
   function ClearInputCom: Boolean;
end;

implementation

uses SysUtils;

constructor TComPort.Create;
begin
inherited;
CloseCom;
end;

destructor TComPort.Destroy;
begin
CloseCom;
inherited;
end;

function TComPort.InitCom(BaudRate, PortNo: Integer; Parity: Char;
CommTimeOuts: TCommTimeouts): Boolean;
var
FileName: string;
DCB: TDCB;
PortParam: string;
begin
result := FALSE;
FileName := 'Com' + IntToStr(PortNo); {имя файла}
hFile := CreateFile(PChar(FileName),
   GENERIC_READ or GENERIC_WRITE, 0, nil,
   OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if hFile = INVALID_HANDLE_VALUE then
   exit;
//установка требуемых параметров
GetCommState(hFile, DCB); //чтение текущих параметров порта
PortParam := 'baud=' + IntToStr(BaudRate) + ' parity=' + Parity +
   ' data=8 stop=1 ' +
   'octs=off';
if BuildCommDCB(PChar(PortParam), DCB) then
begin
   result := SetCommState(hFile, DCB) and
     SetCommTimeouts(hFile, CommTimeOuts);
end;

if not result then
   CloseCom;
end;

procedure TComPort.CloseCom;
begin
if hFile < > INVALID_HANDLE_VALUE then
   CloseHandle(hFile);
hFile := INVALID_HANDLE_VALUE;
end;

function TComPort.ReceiveCom(var Buffer; Size: DWORD): Integer;
var
Received: DWORD;
begin
if hFile = INVALID_HANDLE_VALUE then
   raise Exception.Create('Не открыта запись в Com порт');
if ReadFile(hFile, Buffer, Size, Received, nil) then
begin
   Result := Received;
end
else
   raise Exception.Create('Ошибка приема данных: ' + IntToStr(GetLastError));
end;

function TComPort.SendCom(var Buffer; Size: DWORD): Integer;
var
Sended: DWORD;
begin
if hFile = INVALID_HANDLE_VALUE then
   raise Exception.Create('Не открыта запись в Com порт');
if WriteFile(hFile, Buffer, Size, Sended, nil) then
begin
   Result := Sended;
end
else
   raise Exception.Create('Ошибка передачи данных: ' + IntToStr(GetLastError));
end;

function TComPort.ClearInputCom: Boolean;
begin
if hFile = INVALID_HANDLE_VALUE then
   raise Exception.Create('Не открыта запись в Com порт');
Result := PurgeComm(hFile, PURGE_RXCLEAR);
end;
end.
только порт текст не передает и не принимает, немного другими понятиями он оперирует, проще сделать эмуляцию, но это совсем другая песня
Ответить с цитированием