您的位置:首页 > 其它

在WPF程序中使用系统热键

2010-07-30 10:13 316 查看
写一个能使用系统热键的C/C++程序很容易,然而,用C#/WPF做一个同样的程序却不是那么容易...

原因很简单,WPF Window 没有 WIN32 Window的句柄HWND和消息处理函数WndProc,这使得在WPF程序中调用RegisterHotKey和捕捉WM_HOTKEY消息有点麻烦,浪费了大半天后,终于是解决了问题:

[Flags]
public enum KeyModifiers
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
Windows = 8
}

static class NativeMethod
{
public const int WM_HOTKEY = 0x0312;

[DllImport("user32.dll", EntryPoint = "RegisterHotKey", SetLastError=true)]
public static extern bool RegisterHotKey(IntPtr hwnd, int id, UInt32 fsModifiers, UInt32  vk);

}

public partial class MainWnd : Window
{
public MainWnd()
{
InitializeComponent();
}

void MainWnd_Loaded(object sender, RoutedEventArgs e)
{
InstallHotKey();
}

void InstallHotKey()
{
WindowInteropHelper ih = new WindowInteropHelper(this);
NativeMethod.RegisterHotKey(ih.Handle, 1, (UInt32)(KeyModifiers.Alt | KeyModifiers.Control), (UInt32)KeyInterop.VirtualKeyFromKey(Key.F12));
HwndSource hs = HwndSource.FromHwnd(ih.Handle);
hs.AddHook(new HwndSourceHook(wndproc));
}

IntPtr wndproc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == NativeMethod.WM_HOTKEY)
{
//........
handled = true;
}

return IntPtr.Zero;
}
}


值得注意的是:InstallHotKey()必须在窗口加载后才能调用,否则,ih.Handle可能返回无效的HWND
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: