【问题标题】:How to get the hWnd of Window instance?如何获取 Window 实例的 hWnd?
【发布时间】:2012-05-27 08:47:43
【问题描述】:

我的 WPF 应用程序有多个窗口,我需要能够获取每个 Window 实例的 hWnd 以便在 Win32 API 调用中使用它们。

我想做的例子:

Window myCurrentWindow = Window.GetWindow(this);
IntPtr myhWnd = myCurrentWindow.hWnd; // Except this property doesn't exist.

最好的方法是什么?

【问题讨论】:

标签: c# wpf


【解决方案1】:

WindowInteropHelper 是你的朋友。它有一个接受Window 参数的构造函数和一个返回其窗口句柄的Handle 属性。

Window window = Window.GetWindow(this);
var wih = new WindowInteropHelper(window);
IntPtr hWnd = wih.Handle;

【讨论】:

    【解决方案2】:

    扩展道格拉斯的回答,如果 Window 尚未显示,它可能没有 HWND。您可以使用EnsureHandle() 强制在窗口显示之前创建一个:

    var window = Window.GetWindow(element);
    
    IntPtr hWnd = new WindowInteropHelper(window).EnsureHandle();
    

    注意Window.GeWindow 可以返回null,所以你也应该真正测试一下。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-03
      • 1970-01-01
      • 2011-06-13
      • 1970-01-01
      • 2019-07-08
      • 1970-01-01
      • 2011-07-19
      相关资源
      最近更新 更多