comcontrolunit.pas

来自「群星医药系统源码」· PAS 代码 · 共 96 行

PAS
96
字号
unit ComControlUnit;

interface

uses
  SysUtils, Classes, Spcomm;

type
  TComControl = class(TComponent)
  private
    FComm: TComm;
    FActive: Boolean;
    FCommPort: String;
    FBaudRate: Integer;
    FParityCheck: Boolean;
    procedure SetActive(const Value: Boolean);
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    property CommPort: String read FCommPort write FCommPort; //端口号
    property BaudRate: Integer read FBaudRate write FBaudRate; //通讯波特率
    property ParityCheck: Boolean read FParityCheck write FParityCheck; //奇偶校验
    property Active: Boolean read FActive write SetActive;
    function Open: Boolean;
    function Close: Boolean;
    function Send(mBuffer: PChar; mSize: Word): Boolean;
    function SendStr(mStr: string): Boolean;
  end;

implementation

{ TComControl }

function TComControl.Close: Boolean;
begin
  try
    FComm.StopComm;
    Result := True;
  except
    Result := False;
  end;
  if Result then FActive := False;
end;

constructor TComControl.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FComm := TComm.Create(Self);
  FCommPort := 'COM1';
  FBaudRate := 2400;
  FParityCheck := True;
end;

destructor TComControl.Destroy;
begin
  if Assigned(FComm) then FComm.Free;
end;

function TComControl.Open: Boolean;
begin
  with FComm do try
    CommName := FCommPort;
    BaudRate := FBaudRate;
    Parity := Space;
    ParityCheck := FParityCheck;
    Outx_XonXoffFlow := False;
    Inx_XonXoffFlow := False;
    StartComm;
    Result := True;
  except
    Result := False;
  end;
  FActive := Result;
end;

function TComControl.Send(mBuffer: PChar; mSize: Word): Boolean;
begin
  Result := FComm.WriteCommData(mBuffer, mSize);
end;

function TComControl.SendStr(mStr: string): Boolean;
begin
  Result := Send(PChar(mStr), Length(mStr));
end;

procedure TComControl.SetActive(const Value: Boolean);
begin
  if FActive = Value then Exit;
  FActive := Value;
  if FActive then Open else Close;
end;

end.
 

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?