Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why a message handler doesn't work in debugging mode?

Tags:

delphi

I use berlin in windows 10.

The following message handler works well in a built application but doesn't in debugging mode.

How can I debug the message handler?

type
  TForm1 = class(TForm)
    Memo1: TMemo;
    procedure onReceive(var message: TMessage); message WM_COPYDATA;
  end;

procedure TForm1.onReceive(var message: TMessage);
begin
  Memo1.Lines.Add('a');
end;

The sender code is as follows and the value of the struct is meaningless.

procedure TForm1.FormClick(Sender: TObject);
var
  _Handle: Cardinal;
  _CopyDataStruct: TCopyDataStruct;
begin
  _Handle := FindWindow(nil, 'test form');

  _CopyDataStruct.dwData := 0;
  _CopyDataStruct.cbData := Sizeof(_Handle);
  _CopyDataStruct.lpData := @_handle;

  SendMessage(_Handle, WM_COPYDATA, Handle, integer(@_CopyDataStruct));
end;
like image 677
JO SeongGng Avatar asked Sep 19 '26 19:09

JO SeongGng


1 Answers

If your TForm1 class is open in the IDE's Form Designer, and its Caption is test form in the Object Inspector, then the FindWindow() is likely finding that HWND at runtime instead of the HWND that is inside your running app (you can use GetWindowThreadProcessId() to verify that). Which means you would be sending your message to the wrong HWND. This is a common problem when using FindWindow() to search for a TForm by its caption while running in the debugger. Close the TForm1 source file in the IDE, and then FindWindow() won't be able to find that HWND anymore, it will find the HWND in your running app instead.

And BTW, your _Handle variable needs to be declared as HWND or THandle instead of Cardinal, and the last parameter of SendMessage() needs to be type-cast to LPARAM instead of integer.

like image 108
Remy Lebeau Avatar answered Sep 24 '26 18:09

Remy Lebeau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!