wpf中的全局键
在wpf中的全局键和form中有些差异,所以在这里记录一下,有用到得朋友可以试试!
首先注册APi
代码
1 [DllImport("user32.dll")]
2 public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint control, System.Windows.Forms.Keys keys);
3 [DllImport("user32.dll")]
4 public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
首先在这里事件里注册一个hotkey 并添加windows消息拦截,重点在于在wpf中必须使用
PresentationSource.FromVisual(this) as HwndSource;
来获取source。请注意。
代码
搞定收工!!!!!!
window xp中测试过!!!!!!
1 protected override void OnSourceInitialized(EventArgs e)
2 {
3 base.OnSourceInitialized(e);
4
5 IntPtr handle = new WindowInteropHelper(this).Handle;
6
7 //注册快捷键 0为失败
8 bool isHotKeySuccess = false;
9
10 isHotKeySuccess = RegisterHotKey(handle, MY_HOTKEYID, (UInt32)Hotkey.KeyFlags.Win, System.Windows.Forms.Keys.W);
11
12 //设置 windows消息拦截
13 //HwndSource.FromHwnd(handle).AddHook(new HwndSourceHook(WndProc));
14
15 HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
16
17 source.AddHook(WndProc);
18
19 SetWindowLong(handle, -16, 0);
20 }之后就是要处理你自己的方法就可以了,呵呵!!!代码 /// <summary>
/// Windows消息拦截
/// </summary>
/// <param name="hwnd"></param>
/// <param name="msg"></param>
/// <param name="wParam"></param>
/// <param name="lParam"></param>
/// <param name="handle"></param>
/// <returns></returns>
IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handle)
{
switch (msg)
{
case MY_HOTKEYID:
Executes.WindowShow(TabTypes.None);
break;
}
return IntPtr.Zero;
}