调用delphi程序作为方法

Djo*_*ole 1 delphi freepascal lazarus

这是我编写得很好的简单代码,但会引发访问冲突.它进入MD程序并且调试器显示一些X和Y值,但在退出程序AV后发生.希望有人能提供帮助.

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Controls, Forms,  ExtCtrls;

type
  TForm1 = class(TForm)
    Panel1: TPanel;
    procedure FormCreate(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

    {$R *.dfm}

procedure MD(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
  form1.caption:= inttostr(x)+ ' '+ inttostr(y);
end;

procedure TForm1.FormCreate(Sender: TObject);

function MakeMethod(data, code: pointer): TMethod;
begin
  result.Data:= data;
  result.Code:= code;
end;

begin
  panel1.OnMouseDown:= TMouseEvent(MakeMethod(nil, @MD));
end;

end.
Run Code Online (Sandbox Code Playgroud)

谢谢

klu*_*udg 5

MD签名应包括额外的隐藏参数; 它解决了AV问题.

unit Unit1;

interface

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


type
  TForm1 = class(TForm)
    Panel1: TPanel;
    procedure FormCreate(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure MD(Instance, Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
  form1.caption:= inttostr(x)+ ' '+ inttostr(y);
end;

procedure TForm1.FormCreate(Sender: TObject);

function MakeMethod(data, code: pointer): TMethod;
begin
  result.Data:= data;
  result.Code:= code;
end;

begin
  panel1.OnMouseDown:= TMouseEvent(MakeMethod(nil, @MD));
end;

end.
Run Code Online (Sandbox Code Playgroud)

  • 毫无疑问,使用类方法是更好的解决方案. (2认同)