如何以另一种形式使用RxChar ComPort

时间:2013-01-29 17:14:21

标签: delphi delphi-7 tcomport

我的delphi代码有问题......我有代码:

主要表格

unit MainForm;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, CPort, Menus, ComObj, StdCtrls;

type
  TMainForm = class(TForm)
    MainMenu1: TMainMenu;
    Berkas1: TMenuItem;
    Alat1: TMenuItem;
    erminal1: TMenuItem;
    ComPort1: TComPort;
    Button1: TButton;
    Memo1: TMemo;
    Button2: TButton;
    procedure erminal1Click(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure ComPort1RxChar(Sender: TObject; Count: Integer);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  MainForm: TMainForm;

implementation

uses
  ChildForm;

{$R *.dfm}

procedure TMainForm.erminal1Click(Sender: TObject);
var
  ChildForm: TChildForm;
begin
  ChildForm := TChildForm.Create(Application);
  ChildForm.Show;
end;

procedure TMainForm.Button1Click(Sender: TObject);
begin
  ComPort1.ShowSetupDialog;
end;

procedure TMainForm.ComPort1RxChar(Sender: TObject; Count: Integer);
var
  ComPort: TComPort;
  data: string;
begin
  inherited;
  ComPort := TComPort.Create(Self);
  ComPort1.ReadStr(data, 5);
  ChildForm.Memo1.Text := ChildForm.Memo1.Text+''+data+'';
end;

end.

儿童表格:

unit ChildForm;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ComObj;

type
  TChildForm = class(TForm)
    Memo1: TMemo;
    Button1: TButton;
    Button2: TButton;
    Button3: TButton;
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  ChildForm: TChildForm;

implementation

uses
  MainForm;

{$R *.dfm}

procedure TChildForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  Action := caFree;
end;

procedure TChildForm.Button1Click(Sender: TObject);
begin
  MainForm.ComPort1.Open;
end;

end.

我想将来自我的设备的数据输入显示为子格式的备忘录。我把comport组件放在主窗体中。但是当我运行该程序时,它说:

  

Project Data.exe引发异常类EAccessViolation,并在模块“Data.exe”中显示“地址为00466051的访问冲突”消息。读取地址000002F8'。流程停止了。使用步骤或运行继续。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

评论中提到的代码存在许多问题。

为了更好地实现与comport组件的父/子表单交互, 做如下:

创建一个TDataModule(例如:DataModule1),将comport组件放在那里。

现在,您可以从主窗体和子窗体访问comport组件。

为您的子表单添加私有方法:

procedure TChildForm.ComPort1RxChar(Sender: TObject; Count: Integer);
var
  data: string;
begin
  DataModule1.ComPort1.ReadStr(data, 5);
  Self.Memo1.Text := Self.Memo1.Text+''+data+'';
end;

在子窗体中打开comport时,将comport OnRxChar事件设置为TChildForm.ComPort1RxChar方法。

在TChildForm.OnClose事件中,将comport OnRxChar事件设置为nil并关闭comport。