如何在WPF中将evenHandler设置为所有窗口(整个应用程序)?

Pro*_*mer 3 c# wpf event-handling keydown

如何将事件处理程序(如keydown)设置为整个解决方案,而不是单个窗口?

Mat*_*ton 10

在应用程序类(App.cs)中注册一个全局事件处理程序,如下所示:

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        EventManager.RegisterClassHandler(typeof(Window), Window.KeyDownEvent, new RoutedEventHandler(Window_KeyDown));
    }

    void Window_KeyDown(object sender, RoutedEventArgs e)
    {
        // your code here
    }
}
Run Code Online (Sandbox Code Playgroud)

这将处理您的应用中的KeyDown任何事件Window.您可以e转换KeyEventArgs为获取有关按下的键的信息.