How to retrieve main window handle in WinUI3 app with multiple Views generated by Template studio

62 Views Asked by At

How to retrieve the main window handle in WinUI3 app with multiple Views generated by Template studio? The problem is that when you using multiple views and you would like to invoke some extra dialogs like Save As you are required to provide a main window handle.

1

There are 1 best solutions below

0
Max Zaikin On

Add following code in App.xaml.cs

//Retrieve the main window handle (HWND) of the current WinUI 3 window.
public static IntPtr hWnd => MainWindow.GetWindowHandle();

I added mine right below following line in App.xaml.cs file:

public static WindowEx MainWindow { get; } = new MainWindow();

Now you are able to get MainWindow hWnd value from anywhere in your solution just simply calling App.hWnd

for example calling from DataGrid.xaml.cs:

      // Initialize the file save picker with the window handle (HWND).
    
    WinRT.Interop.InitializeWithWindow.Initialize(savePicker, App.hWnd);

Best regards, Maks.