检索窗口句柄 (HWND) - Windows apps

beat365手机下载 📅 2025-08-12 19:40:25 👤 admin 👁️ 1257 ❤️ 68
检索窗口句柄 (HWND) - Windows apps

本主题介绍如何在桌面应用中检索窗口的窗口句柄。 范围涵盖 WinUI 3、Windows Presentation Foundation (WPF) 和 Windows Forms (WinForms)应用;代码示例以 C# 和 C++/WinRT 形式提供。

上述开发和 UI 框架(在幕后)都是基于 Win32 API 构建的。 在 Win32 中,窗口对象由一个称为窗口句柄的值来标识。 而窗口句柄的类型是 HWND(尽管它以 C# 形式显示为 IntPtr)。 在任何情况下,都会听到 HWND 这个术语,它是窗口句柄的简称。

在 WinUI 3、WPF 或 WinForms 桌面应用中检索窗口的 HWND 有多种原因。 其中一个例子是使用 HWND 与依赖 CoreWindow 显示用户界面 (UI) 的某些 Windows Runtime (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

// 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。

相关主题

显示依赖于 CoreWindow 的 WinRT UI 对象

从 .NET 应用调用互操作 API

WinUI 3

Windows Presentation Foundation (WPF)

Windows 窗体 (WinForms)

C++/WinRT

Win32 API

相关养生推荐

风龙废墟
365bet体育官网平台

风龙废墟

📅 07-14 👁️ 1371
世界杯的人气榜(全球球迷热情高涨的排名榜单)
365bet体育官网平台

世界杯的人气榜(全球球迷热情高涨的排名榜单)

📅 07-28 👁️ 3979
衙的意思,衙的解释,衙的拼音,衙的部首,衙的笔顺
beat365手机下载

衙的意思,衙的解释,衙的拼音,衙的部首,衙的笔顺

📅 07-24 👁️ 3322
qq邮箱文件夹怎么发送
365bet体育官网平台

qq邮箱文件夹怎么发送

📅 07-20 👁️ 692
9 个技巧轻松修复 iPhone 白屏死机(更新)
beat365手机下载

9 个技巧轻松修复 iPhone 白屏死机(更新)

📅 08-04 👁️ 2518
gta5怎么注册账号
365bet体育官网平台

gta5怎么注册账号

📅 06-29 👁️ 372