WinUI - ウインドウハンドル (HWND) を取得する

C++ で WinUI 3 ライブラリを使う

ウィンドウハンドルを取得する方法を紹介します。

ウィンドウハンドルは IWindowNative::get_WindowHandle で取得できるので、関数にしてみました。

また IWindowNative クラスは microsoft.ui.xaml.window.h で定義されているのでインクルードします。 winrt フォルダ下の winrt/Microsoft.UI.Xaml.~ ではないので間違えないようにしましょう。

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

/// IWindowNative を実装するオブジェクトによって表されるウィンドウのウィンドウハンドル (HWND) を取得します。
template<typename T>
auto getHwnd(T pWnd) -> HWND
{
    HWND hWnd = 0;
    if (auto p = pWnd->try_as<::IWindowNative>(); p) {
        p->get_WindowHandle(&hWnd);
    }
    return hWnd;
}

このように使います。

void MainWindow::myButton_Click(IInspectable const&, RoutedEventArgs const&)
{
    auto hWnd = getHwnd(this);
}

参考

WinUI 3 with C++ 入門 - ビリヤードが好きなプログラマー

IWindowNative::get_WindowHandle - Windows App SDK | Microsoft Learn

ウィンドウ ハンドルを取得する (HWND) - Windows apps | Microsoft Learn