How to get HWND handler from content page in MAUI

Yang Yang 46 Reputation points
2022-06-14T11:58:49.957+00:00

I have a HWND written by C++ and we hope added it to content page in MAUI, so how should we handle this case?

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
2,844 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rob Caplan - MSFT 5,412 Reputation points Microsoft Employee
    2022-06-14T17:42:04.927+00:00

    I'm not sure what you mean by "adding it to content page". In the future can you please provide more details on what specifically you are trying to do? See How to write a quality question

    That said, HWNDs and ContentPages work at different levels. There isn't a direct mapping, and you can't host an HWND in a MAUI control or vice versa. MAUI on Windows uses WinUI 3. There is an HWND for the top-level Window, but children of that Windows (such as a ContentPage) are windowless controls and don't have HWNDs.

    See MAUI Fundementals Windows for more on the Window object.
    See [Manage app windows (Windows App SDK) / UI framework and HWND interop](https://learn.microsoft.com/en-us/windows/apps/windows-app-sdk/windowing/windowing-overview#ui-framework-and-hwnd-interop]
    See Retrieve a window handle (HWND) / WinUI 3 with C++ for how to get an HWND from a WinUI Window.

    To get the top-level window you need to drop out of MAUI into platform specific code and get the WinUI WindowHandle from the Window's Handler's PlatformView. Obviously non-Windows platforms won't have HWNDs.

    #if WINDOWS  
    		var hwnd = ((MauiWinUIWindow)App.Current.Windows[0].Handler.PlatformView).WindowHandle;  
    #endif  
    

0 additional answers

Sort by: Most helpful