最近,对wpf添加快捷键的方式进行了整理。主要用到的三种方式如下:
一、wpf命令:
资源中添加命令 <Window.Resources> <RoutedUICommand x:Key="ToolCapClick" Text="截屏快捷键" /> </Window.Resources> 输入命令绑定 <Window.InputBindings> <KeyBinding Gesture="Ctrl+Alt+Q" Command="{StaticResource ToolCapClick}"/> </Window.InputBindings> 命令执行方法绑定 <Window.CommandBindings> <CommandBinding Command="{StaticResource ToolCapClick}" CanExecute="CommandBinding_ToolCapClick_CanExecute" Executed="CommandBinding_ToolCapClick_Executed"/> </Window.CommandBindings>
需要注意的是,绑定命令的时候,也可以<KeyBinding Modifiers="Ctrl+Alt" Key="Q" Command="{StaticResource ToolCapClick}"/>,建议用前者,以免造成混乱。
执行方法实现
#region 截屏快捷键 private void CommandBinding_ToolCapClick_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = true; } private void CommandBinding_ToolCapClick_Executed(object sender, ExecutedRoutedEventArgs e) { try { CaptureImageTool capture = new CaptureImageTool(); capture.CapOverToHandWriting += Capture_CapOverToHandWriting; capture.CapOverToBlackboard += Capture_CapOverToBlackboard; string saveName = String.Empty; if (capture.ShowDialog() == System.Windows.Forms.DialogResult.OK) { //保存截取的内容 System.Drawing.Image capImage = capture.Image; //上课存班级内部,不上课存外部 string strSavePath = DataBusiness.GetCurrentTeachFilePath(SystemConstant.PATH_CAPS); if (!String.IsNullOrEmpty(strSavePath)) { if (!Directory.Exists(strSavePath)) { Directory.CreateDirectory(strSavePath); } saveName = strSavePath + DateTime.Now.ToString(SystemConstant.FORMAT_CAPS); } else { saveName = PathExecute.GetPathFile(SystemConstant.PATH_SAVE + Path.DirectorySeparatorChar + SystemConstant.PATH_CAPS, DateTime.Now.ToString(SystemConstant.FORMAT_CAPS)); } capImage.Save(saveName + SystemConstant.EXTENSION_PNG, System.Drawing.Imaging.ImageFormat.Png); } } catch (Exception ex) { new Exception("capscreen module error:" + ex.Message); } }
二、利用windows钩子(hook)函数
第一步 引入到Winows API
1: [DllImport("user32.dll")]
2: public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
3: [DllImport("user32.dll")]
4: public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
这边可以参考两个MSDN的链接
第一个是关于RegisterHotKey函数的,里面有关于id,fsModifiers和vk 的具体说明
http://msdn.microsoft.com/en-us/library/windows/desktop/ms646309%28v=vs.85%29.aspx
第二个是Virtual-Key 的表,即RegisterHotKey的最后一个参数
http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731%28v=vs.85%29.aspx
第二步 注册全局按键
这里先介绍一个窗体的事件SourceInitialized,这个时间发生在WPF窗体的资源初始化完毕,并且可以通过WindowInteropHelper获得该窗体的句柄用来与Win32交互。
具体可以参考MSDN http://msdn.microsoft.com/en-us/library/system.windows.window.sourceinitialized.aspx
我们通过重载OnSourceInitialized来在SourceInitialized事件发生后获取窗体的句柄,并且注册全局快捷键
private const Int32 MY_HOTKEYID = 0x9999; protected override void OnSourceInitialized(EventArgs e) { base.OnSourceInitialized(e); IntPtr handle = new WindowInteropHelper(this).Handle; RegisterHotKey(handle, MY_HOTKEYID, 0x0001, 0x72); }
关于几个常熟的解释
MY_HOTKEYID 是一个自定义的ID,取值范围在0x0000 到 0xBFFF。之后我们会根据这个值来判断事件的处理。
RegisterHotKey的第三或第四个参数可以参考第一步
第三步 添加接收所有窗口消息的事件处理程序
上面只是在系统中注册了快捷键,但是还要获取消息的事件,并筛选消息。
继续在OnSourceInitialized函数中操作
protected override void OnSourceInitialized(EventArgs e) { base.OnSourceInitialized(e); IntPtr handle = new WindowInteropHelper(this).Handle; RegisterHotKey(handle, MY_HOTKEYID, 0x0001, 0x72); HwndSource source = PresentationSource.FromVisual(this) as HwndSource; source.AddHook(WndProc); }
下面来完成WndProc函数
IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handle) { //Debug.WriteLine("hwnd:{0},msg:{1},wParam:{2},lParam{3}:,handle:{4}" // ,hwnd,msg,wParam,lParam,handle); if(wParam.ToInt32() == MY_HOTKEYID) { //全局快捷键要执行的命令 } return IntPtr.Zero; }
三、给button控件添加快捷键
<UserControl.Resources> <RoutedUICommand x:Key="ClickCommand" Text="点击快捷键" /> </UserControl.Resources> <UserControl.CommandBindings> <CommandBinding Command="{StaticResource ClickCommand}" Executed="ClickHandler" /> </UserControl.CommandBindings> <UserControl.InputBindings> <KeyBinding Key="C" Modifiers="Ctrl" Command="{StaticResource ClickCommand}" /> </UserControl.InputBindings> <Grid> <Button Content="button" Command="{StaticResource ClickCommand}"/> </Grid>
执行方法:
private void ClickHandler(object sender, RoutedEventArgs e) { Message.Show("命令执行!"); }