c++winrt-xamldesktop-applicationwinui-3c++-winrt

How to get Main Window Handle on Page in WinUI 3 Using C++


I am working on a WinUI 3 demo using C++.

enter image description here

I want to get a Main or Native Window Handler to open a Picker within a Page.

The code block which I am using works fine on Window but it does not work on Page.

auto windowNative{ this->try_as<::IWindowNative>()};
winrt::check_bool(windowNative);
HWND hWnd{ 0 };
windowNative->get_WindowHandle(&hWnd);

Help me to get MainWindow Handler in Page1.xaml.cpp


Solution

  • Only Window implements IWindowNative, so you need to pass the window reference around, or if you're sure there's only one Window in your process, you can use a code like this:

    HWND GetProcessFirstWindowHandle(DWORD pid = 0)
    {
        struct ProcessWindow { DWORD pid;  HWND hWnd; } pw = {};
        pw.pid = pid ? pid : GetCurrentProcessId();
        EnumWindows([](auto hWnd, auto lParam)
            {
                DWORD pid;
                GetWindowThreadProcessId(hWnd, &pid);
                if (pid != ((ProcessWindow*)lParam)->pid)
                    return TRUE;
    
                ((ProcessWindow*)lParam)->hWnd = hWnd;
                return FALSE;
            }, (LPARAM)&pw);
        return pw.hWnd;
    }
    

    And for example, call it simply like this:

    void MainWindow::myButton_Click(IInspectable const&, RoutedEventArgs const&)
    {
        auto hwnd = GetProcessFirstWindowHandle();
    }
    

    You can also add some check on class name, like what's done in this answer (it's C# but the code is already using interop to access native Windows APIs) : Retrive Window Handle in Class Library WinUI3