C# 如何获得窗口的HWND

C# 如何获得窗口的HWND,c#,wpf,hotkeys,C#,Wpf,Hotkeys,我有一段在Winform上运行的代码: 公共类全局热键 { 私有整数修饰符; 私钥; 私人IntPtr hWnd; 私有int-id; 公共全局热键(整型修饰符、键、窗体) { this.modifier=修饰符; this.key=(int)键; this.hWnd=form.Handle; id=this.GetHashCode(); } 公共布尔寄存器() { 返回寄存器hotkey(hWnd、id、修饰符、key); } 公共bool注销器() { 返回未注册的热键(hWnd,id);

我有一段在Winform上运行的代码:

公共类全局热键
{
私有整数修饰符;
私钥;
私人IntPtr hWnd;
私有int-id;
公共全局热键(整型修饰符、键、窗体)
{
this.modifier=修饰符;
this.key=(int)键;
this.hWnd=form.Handle;
id=this.GetHashCode();
}
公共布尔寄存器()
{
返回寄存器hotkey(hWnd、id、修饰符、key);
}
公共bool注销器()
{
返回未注册的热键(hWnd,id);
}
公共覆盖int GetHashCode()
{
返回修饰符^key^hWnd.ToInt32();
}
[DllImport(“user32.dll”)]
私有静态外部bool寄存器hotkey(IntPtr hWnd、intid、intfsmodifiers、intvk);
[DllImport(“user32.dll”)]
私有静态外部bool unregister热键(IntPtr hWnd,intid);
}
初始化组件之后
我就这样初始化它:

ghk=newglobalhotkey(Constants.CTRL+Constants.SHIFT,Keys.A,this);
我有一个WPF项目,我想使用同一个类,所以我尝试以这种方式更改构造函数:

公共全局热键(int修饰符、键、System.Windows.Window窗体)
{
this.modifier=修饰符;
this.key=(int)键;
this.hWnd=form.Handle;
id=this.GetHashCode();
}
但我在这一行有一个编译时错误:

this.hWnd = form.Handle;
严重性代码说明项目文件行抑制状态 错误CS1061“窗口”不包含“句柄”和的定义 没有可访问的扩展方法“Handle”接受的第一个参数为 找不到类型“Window”(是否缺少using指令或 装配参考?)

使用WPF,类的存在是为了获得所需的句柄

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

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

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
作为句柄传递。

我需要在哪里使用这两行?这将替换win forms
this.hWnd=form.handle
我的函数签名仍然是全局热键(int修饰符、键、表单)我有编译错误:严重性代码描述项目文件行抑制状态错误CS1503参数1:无法从“热键.classes.core.GlobalHotkey”转换为“System.Windows.Window”当然,您还需要用WPFWindow替换表单。可能是