检索窗口句柄 (HWND)

本主题介绍如何在桌面应用中获取窗口的窗口句柄。 范围涵盖 WinUI 3Windows Presentation Foundation(WPF)Windows 窗体(WinForms) 应用;代码示例显示在 C# 和 C++/WinRT 中。

上面列出的开发和 UI 框架是在 Win32 API 上构建的(幕后)。 在 Win32 中, 窗口 对象由称为 窗口句柄的值标识。 窗口句柄的类型是 HWND (尽管它以 C# 形式显示为 IntPtr)。 在任何情况下,您都会听到HWND作为窗口句柄的简写词。

在 WinUI 3、WPF 或 WinForms 桌面应用中,有多种原因需要检索窗口的 HWND。 一个示例是使用 HWND 与依赖于 CoreWindow 显示用户界面(UI)的某些 Windows 运行时(WinRT)对象进行互作。 有关详细信息,请参阅 显示依赖于 CoreWindow 的 WinRT UI 对象

使用 C# 的 WinUI 3

下面的 C# 代码演示如何检索 WinUI 3 Window 对象的窗口句柄(HWND)。 此示例在 WinRT.Interop.WindowNative C# 互作类上调用 GetWindowHandle 方法。 有关 C# 互作类的详细信息,请参阅 从 .NET 应用调用互作 API

// MainWindow.xaml.cs
private async void myButton_Click(object sender, RoutedEventArgs e)
{
    // Retrieve the window handle (HWND) of the current WinUI 3 window.
    var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
}

具有 C++ 的 WinUI 3

下面的 C++/WinRT 代码演示如何检索 WinUI 3 Window 对象的窗口句柄(HWND)。 此示例调用 IWindowNative::get_WindowHandle 方法。

// pch.h
...
#include <microsoft.ui.xaml.window.h>

// MainWindow.xaml.cpp
void MainWindow::myButton_Click(IInspectable const&, RoutedEventArgs const&)
{
    // Retrieve the window handle (HWND) of the current WinUI 3 window.
    auto windowNative{ this->m_inner.as<::IWindowNative>() };
    HWND hWnd{ 0 };
    windowNative->get_WindowHandle(&hWnd);
}

使用 C# 的 WPF

下面的 C# 代码演示如何检索 WPF 窗口对象的窗口句柄(HWND)。 此示例使用 WindowInteropHelper 类。

// MainWindow.xaml.cs
private void Button_Click(object sender, RoutedEventArgs e)
{
    var wih = new System.Windows.Interop.WindowInteropHelper(this);
    var hWnd = wih.Handle;
}

使用 C# 的 WinForms

下面的 C# 代码演示如何检索 WinForms 窗体对象的窗口句柄(HWND)。 此示例使用 NativeWindow.Handle 属性。

// Form1.cs
private void button1_Click(object sender, EventArgs e)
{
    var hWnd = this.Handle;
}

确定承载视觉元素的窗口

从视觉元素中,可以访问UIElement.XamlRoot,然后XamlRoot.ContentIslandEnvironment,然后ContentIslandEnvironment.AppWindowId属性包含顶级 Win32 HWND 的ID。