如何在WPF中使用热键

问题描述 投票:0回答:1

所以我有这段代码适用于Winform

public class GlobalHotkey
    {
        private int modifier;
        private int key;
        private IntPtr hWnd;
        private int id;

        public GlobalHotkey(int modifier, Keys key, Form form)
        {
            this.modifier = modifier;
            this.key = (int)key;
            this.hWnd = form.Handle;
            id = this.GetHashCode();
        }

        public bool Register()
        {
            return RegisterHotKey(hWnd, id, modifier, key);
        }

        public bool Unregiser()
        {
            return UnregisterHotKey(hWnd, id);
        }

        public override int GetHashCode()
        {
            return modifier ^ key ^ hWnd.ToInt32();
        }

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

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

InitializeComponent之后,我就这样启动它:

ghk = new GlobalHotkey(Constants.CTRL + Constants.SHIFT, Keys.A, this);

因此,如果我有WPF项目,并且我想使用它,我尝试以这种方式更改构造函数:

public GlobalHotkey(int modifier, Keys key, System.Windows.Window form)
{
    this.modifier = modifier;
    this.key = (int)key;
    this.hWnd = form.Handle;
    id = this.GetHashCode();
}

但是我在这行有编译错误

this.hWnd = form.Handle;

严重级别描述项目文件行抑制状态错误CS1061“窗口”不包含“句柄”的定义,并且没有可访问的扩展方法'Handle'接受第一个参数可以找到“窗口”类型(您是否缺少using指令或程序集参考?)

wpf hotkeys
1个回答
1
投票

使用WPF,存在WindowInteropHelper类以获取所需的句柄。

此类的成员允许调用者对Win32 HWND和WPF窗口的父HWND。

创建WindowInteropHelper后,您可以像使用Form一样使用它的手柄。在您的情况下,构造函数应如下所示:

public GlobalHotkey(int modifier, Keys key, Window window)
{
    this.modifier = modifier;
    this.key = (int)key;
    //Use handle to register or unregister hotkey
    var helper = new WindowInteropHelper(window);
    this.hWnd = helper.Handle;
    id = this.GetHashCode();
}   

请注意,如果特定窗口不需要接收热键,也可以将IntPtr.Zero作为句柄传递。

© www.soinside.com 2019 - 2024. All rights reserved.