[英]Global hotkeys in WPF working from every window
我必須使用可在每個窗口和講台上使用的熱鍵。 在Winforms中,我使用了:
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應用程序中,我嘗試執行以下操作:
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
}
}
但是它僅在我的應用程序處於活動狀態且位於頂部時才起作用,但是在最小化該應用程序時(例如),它不起作用。 有什么辦法嗎?
您可以使用與WinForms中相同的方法進行一些修改:
WindowInteropHelper
獲取HWND
(而不是窗體的Handle
屬性) HwndSource
處理窗口消息(而不是覆蓋窗體的WndProc
) WPF
Key
枚舉-它的值不是您想要的值 完整的代碼:
[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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.