如何设置一个事件处理程序(如keydown
),以完整的解决方案,而不是一个单一的窗口?
Answer 1:
在您的应用程序类(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
}
}
这将处理KeyDown
事件的任何Window
在您的应用程序。 你可以投e
到KeyEventArgs
获得约按键的信息。
Answer 2:
这个怎么样:
public partial class App : Application {
protected override void OnStartup(StartupEventArgs e) {
EventManager.RegisterClassHandler(typeof(Window), Window.KeyDownEvent, new RoutedEventHandler(KeyDown));
base.OnStartup(e);
}
void KeyDown(object sender, RoutedEventArgs e) {
}
}
Answer 3:
你应该用一个委托,连接事件(无论它是),并在事件跳转功能您愿意工作。
只要你想你的代理,你可以加载尽可能多的事件。
MZE。
Answer 4:
那么, KeyDown
将只在当前窗口,因为你需要关注的KeyDown
。 你可以做的是添加一个处理所有的Windows和调度在那些处理其他事件,然后注册,你需要这个新事件的所有类。
此外,您可以看看Observer
模式
Answer 5:
你不能。
Eighter您注册的所有窗口的事件,并把它传递给全局函数/事件或(在该keydown的情况下或类似)你使用一些全球性的“事件捕获”(如本的键盘)。
文章来源: How to set an evenHandler in WPF to all windows (entire application)?