I want to call a method that is sent as a parameter through a window message. I tried as in the example below... but I get access violation when the DoWork
method is executed. I think the procedural CallBack
variable is not reconstructed properly in the message handler. In Delphi documentation it says that a "method pointer" variable has 2 pointers: "These types represent method pointers. A method pointer is really a pair of pointers; the first stores the address of a method, and the second stores a reference to the object the method belongs to."... But I don't know how to access the second pointer, and then reconstruct the variable with those two pointers...
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TCallBackNotify = function(CallBack: Pointer = nil): Boolean of object;
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
procedure Test(var Msg: TMessage); message WM_USER;
function DoWork(CallBack: Pointer = nil): Boolean;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Test(var Msg: TMessage);
var CallBack: TCallBackNotify;
begin
if Msg.Msg = WM_USER then begin
@CallBack:= Pointer(Msg.WParam);
CallBack;
end;
end;
function TForm1.DoWork(CallBack: Pointer = nil): Boolean;
begin
Caption:= 'It''s working !';
end;
procedure TForm1.Button1Click(Sender: TObject);
var CallBack: TCallBackNotify;
begin
CallBack:= DoWork;
PostMessage(Handle, WM_USER, WPARAM(@CallBack) , 0);
end;
end.