要在WPF和.NET 3.5中注册全局热键,可以使用RegisterHotKey
函数。以下是一个示例代码,展示了如何注册全局热键CTRL + SHIFT + (LETTER):
using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Input;
namespace GlobalHotKeyExample
{
public partial class MainWindow : Window
{
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
private const int WM_HOTKEY = 0x0312;
public MainWindow()
{
InitializeComponent();
ComponentDispatcher.ThreadPreprocessMessage += ComponentDispatcher_ThreadPreprocessMessage;
// 注册全局热键
RegisterHotKey(new KeyGesture(Key.A, ModifierKeys.Control | ModifierKeys.Shift));
}
private void ComponentDispatcher_ThreadPreprocessMessage(ref MSG msg, ref bool handled)
{
if (msg.message == WM_HOTKEY)
{
int id = (int)msg.wParam;
// 在这里处理热键事件
MessageBox.Show("全局热键被按下!");
}
}
protected override void OnClosed(EventArgs e)
{
ComponentDispatcher.ThreadPreprocessMessage -= ComponentDispatcher_ThreadPreprocessMessage;
base.OnClosed(e);
}
private void RegisterHotKey(KeyGesture keyGesture)
{
int keyCode = KeyInterop.VirtualKeyFromKey(keyGesture.Key);
uint modifiers = 0;
if ((keyGesture.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
{
modifiers |= (uint)Win32.MOD_CONTROL;
}
if ((keyGesture.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift)
{
modifiers |= (uint)Win32.MOD_SHIFT;
}
if (!RegisterHotKey(this.GetHandle(), keyCode, modifiers, keyCode))
{
throw new Exception("注册热键失败!");
}
}
private IntPtr GetHandle()
{
return new WindowInteropHelper(this).Handle;
}
}
}
在这个示例中,我们使用了RegisterHotKey
函数来注册全局热键。我们还使用了ComponentDispatcher.ThreadPreprocessMessage
事件来处理热键事件。
注意:这个示例代码仅适用于WPF和.NET 3.5。如果您使用的是其他框架或版本,可能需要进行一些调整。
领取专属 10元无门槛券
手把手带您无忧上云