检索窗口句柄 (HWND)

本主题介绍如何在桌面应用中检索窗口的窗口句柄。 范围涵盖 Windows UI 库 (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);
}

WPF 与 C#

下面的 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;
}