Application-wide message handler in C# WinForms application

1.2k views Asked by At

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.

1

There are 1 answers

0
David Heffernan On BEST ANSWER

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.