【问题标题】:How to get HWND for window如何获取窗口的 HWND
【发布时间】:2020-02-03 21:31:09
【问题描述】:

我有这段代码适用于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 'Window' 不包含 'Handle' 的定义和 没有可访问的扩展方法“句柄”接受第一个参数 可以找到类型“窗口”(您是否缺少 using 指令或 汇编参考?)

【问题讨论】:

标签: c# wpf hotkeys


【解决方案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 作为句柄传递。

【讨论】:

  • 我需要在哪里使用这 2 行?
  • 这取代了win表格this.hWnd = form.Handle
  • 我的函数签名仍然是 GlobalHotkey(int modifier, Keys key, Form form) 并且我有编译错误:严重代码描述项目文件行抑制状态错误 CS1503 参数 1:无法从 'Hotkeys.classes 转换.core.GlobalHotkey' 到 'System.Windows.Window'
  • 当然,您还需要将 Form 替换为 WPF Window
猜你喜欢
  • 2013-07-13
  • 2013-01-17
  • 1970-01-01
  • 1970-01-01
  • 2020-10-22
  • 2011-01-21
  • 1970-01-01
  • 1970-01-01
  • 2011-08-14
相关资源
最近更新 更多