天天看点

WPF UserControl响应窗体的PreviewKeyDown事件

目的

在UserControl页面实现通过快捷键打开新建窗口

实现过程

监听Window窗体的PreviewKeyDown

其实,使用KeyDown事件也是可以的

页面代码

<Window x:Class="WpfApp2.MainWindow" PreviewKeyDown="Window_PreviewKeyDown" ......>

后置页代码

private void Window_PreviewKeyDown(object sender, KeyEventArgs e)

{

if (this.ShowContent.Content is BaseUserControl control) control.ListenWindowKeyDown(e);

}

UserControl基类

BaseUserControl继承自UserControl,定义了虚方法,以便重写

public virtual void ListenWindowKeyDown(KeyEventArgs e)

{

//如果需要使用事件,需要重写,此处不做任何处理

}

UserControl调用 KeyDown

// 监听窗口KeyDown事件

public override void ListenWindowKeyDown(KeyEventArgs e)

{

//DEMO

if (Keyboard.IsKeyDown(Key.LeftAlt) && Keyboard.IsKeyDown(Key.N)) { //TODO }

}

到此完成,具体的快捷键触发就不写了

参考

https://blog.csdn.net/BYH371256/article/details/89394198

WPFの三种方式实现快捷键

https://www.cnblogs.com/lonelyxmas/p/9941791.html

WPF UserControl响应PreviewKeyDown事件方法

转载于:https://www.cnblogs.com/xcsn/p/10768903.html

c#