Question

In Delphi 6 I could set an application-wide message handler:

procedure TFrmMain.TntFormShow(Sender: TObject);
begin
  Application.OnMessage:=AppMsgHandler;
end;

procedure TFrmMain.AppMsgHandler(var Msg:TMsg; var Handled:Boolean);
begin
  if Msg.message=WM_KEYDOWN then begin
    ..............
  end;
  if Msg.message=WM_KEYUP then begin
    ..............
  end;
end;

This handler makes possible handling of keyboard events regardless which control or even which form of the application is active. Note that it is not a global system-wide keyboard hook and therefore is not so dangerous.

Now the question: How could be the same done in C# WinForms application?

I could override WndProc of a form but this solution does not catch any keydown and keyup events.

I could also override ProcessCmdKey of a form but it does not catch WM_KEYUP.

Also both of the solutions are applied to one form class only and I need an application-wide solution.

Was it helpful?

Solution

You can use Application.AddMessageFilter to register a message filter. From the documentation:

Use a message filter to prevent specific events from being raised or to perform special operations for an event before it is passed to an event handler. Message filters are unique to a specific thread.

To prevent a message from being dispatched, the value parameter instance that you pass to this method must override the PreFilterMessage method with the code to handle the message. The method must return false.

This offers exactly the same functionality as Delphi's OnMessage event.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top