gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:02:00 24 4
gpt4 key购买 nike

在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com