2012-07-07 88 views
9

我必须使用热键,它将在每个窗口和讲台上工作。在的WinForms我用:WPF中的全局热键从每个窗口工作

RegisterHotKey(this.Handle, 9000, 0x0002, (int)Keys.F10); 

UnregisterHotKey(this.Handle, 9000); 

protected override void WndProc(ref Message m) 
{ 
    base.WndProc(ref m); 
    switch (m.Msg) 
    { 
     case 0x312: 
     switch (m.WParam.ToInt32()) 
     { 
      case 9000: 
      //function to do 
      break; 
     } 
     break; 
    } 
} 

在我的WPF aplication我试着这样做:

AddHandler(Keyboard.KeyDownEvent, (KeyEventHandler)HandleKeyDownEvent); 

private void HandleKeyDownEvent(object sender, KeyEventArgs e) 
{ 
    if (e.Key == Key.F11 && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control) 
    { 
     //function to do 
    } 
}  

但是,它只在我的应用程序处于活动状态并位于顶部时才起作用,但在应用程序最小化时(例如)它不起作用。有没有办法做到这一点?

回答

20

您可以使用相同的方法与一些适应的WinForms:

  • 使用WindowInteropHelper得到(形式的Handle属性代替)
  • 使用HwndSource处理窗口消息(HWND而不是覆盖一种形式)
  • 不使用Key枚举从WPFWndProc - 它的价值观是不是那些你想

完整代码:

[DllImport("User32.dll")] 
private static extern bool RegisterHotKey(
    [In] IntPtr hWnd, 
    [In] int id, 
    [In] uint fsModifiers, 
    [In] uint vk); 

[DllImport("User32.dll")] 
private static extern bool UnregisterHotKey(
    [In] IntPtr hWnd, 
    [In] int id); 

private HwndSource _source; 
private const int HOTKEY_ID = 9000; 

protected override void OnSourceInitialized(EventArgs e) 
{ 
    base.OnSourceInitialized(e); 
    var helper = new WindowInteropHelper(this); 
    _source = HwndSource.FromHwnd(helper.Handle); 
    _source.AddHook(HwndHook); 
    RegisterHotKey(); 
} 

protected override void OnClosed(EventArgs e) 
{ 
    _source.RemoveHook(HwndHook); 
    _source = null; 
    UnregisterHotKey(); 
    base.OnClosed(e); 
} 

private void RegisterHotKey() 
{ 
    var helper = new WindowInteropHelper(this); 
    const uint VK_F10 = 0x79; 
    const uint MOD_CTRL = 0x0002; 
    if(!RegisterHotKey(helper.Handle, HOTKEY_ID, MOD_CTRL, VK_F10)) 
    { 
     // handle error 
    } 
} 

private void UnregisterHotKey() 
{ 
    var helper = new WindowInteropHelper(this); 
    UnregisterHotKey(helper.Handle, HOTKEY_ID); 
} 

private IntPtr HwndHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) 
{ 
    const int WM_HOTKEY = 0x0312; 
    switch(msg) 
    { 
     case WM_HOTKEY: 
      switch(wParam.ToInt32()) 
      { 
       case HOTKEY_ID: 
        OnHotKeyPressed(); 
        handled = true; 
        break; 
      } 
      break; 
    } 
    return IntPtr.Zero; 
} 

private void OnHotKeyPressed() 
{ 
    // do stuff 
} 
+0

它的工作,谢谢了很多 – cadi2108 2012-07-08 09:15:40