Delphi custom message handlers

JosephStyons picture JosephStyons · May 13, 2009 · Viewed 15k times · Source

When a user double-clicks a dbgrid, I show a non-modal form.

When they close that form, I want to refresh the grid.

To accomplish that, I have tried the following:

1 - Define a custom message constant:

const
  WM_REFRESH_MSG = WM_USER + 1;  //defined in a globally available unit

2 - In the OnClose event of my non-modal form, I have this:

procedure TMyNonModalForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  PostMessage(Self.Handle,WM_REFRESH_MSG,0,0);
end;

3 - In the private declarations of the form that holds the dbGrid, I have this:

procedure OnRefreshRequest(var Msg: TMessage); message WM_REFRESH_MSG;

...

procedure TMyFormWithADBGrid.OnRefreshRequest(var Msg: TMessage);
begin
  RefreshGrid;
end;

After doing these things, the PostMessage fires fine, but the OnRefreshRequest procedure never runs. What am I doing wrong?

Answer

Frederik Slijkerman picture Frederik Slijkerman · May 14, 2009

Note that WM_USER is not the correct constant to base your own messages on, unless you are writing a custom control directly descending from TWinControl. Use WM_APP instead.

Also, it's considered good style to use UM_ for User Message instead of WM_ because that prefix is supposed to be reserved for the Windows header files.