c# - C# WinForms 应用程序中的应用程序范围的消息处理程序

标签 c# winforms delphi handler windows-messages

在 Delphi 6 中,我可以设置应用程序范围的消息处理程序:

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;

这个处理程序使得键盘事件的处理成为可能,而不管哪个控件或什至是哪种形式的应用程序处于事件状态。请注意,它不是全局系统范围的键盘钩子(Hook),因此并不那么危险。

现在的问题是:如何在 C# WinForms 应用程序中完成相同的操作?

我可以覆盖表单的 WndProc,但此解决方案不会捕获任何 keydown 和 keyup 事件。

我也可以覆盖表单的 ProcessCmdKey,但它不会捕获 WM_KEYUP

此外,这两种解决方案都只适用于一个表单类,我需要一个应用程序范围的解决方案。

最佳答案

您可以使用 Application.AddMessageFilter注册消息过滤器。来自文档:

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.

这提供了与 Delphi 的 OnMessage 事件完全相同的功能。

关于c# - C# WinForms 应用程序中的应用程序范围的消息处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20410740/

相关文章:

c# - 网站速度测试。 gzip 有问题吗?

c# - 使用 EF Core 在 linq 中使用索引嵌套选择投影

vb.net - WinForms 深度嵌套控件调整内核大小错误 - 拆分器面板无法正确缩放控件

Delphi在DBGrid的Row前面添加图像

c# - 用不同的时间步重现重力物理结果

c# - 是否有 C++ 的 System.Diagnostics.EventLog 等效项?

.net - 可以访问 VB.NET 类库中的 My.Forms 对象吗?

c# - 更改数据集中记录的顺序

delphi - Eureka 日志 : save exception stacktrace into a log file

delphi - 即使 Windows 7 Flip 3D 已激活,如何使表单始终位于顶部