Search code examples
c#navigationviewhwndwinui-3mainwindow

How to retrieve the window handle of the current WinUI 3 MainWindow from a page in a frame in a NavigationView control on the MainWindow


I am creating my first WinUI 3 desktop application. I have a NavigationView on my MainWindow. I have 9 different pages that I navigate to via the frame in the NavigationView. One of the pages is for printing reports. I need to get the FileSavePicker to work from the 'reportPage'. I have implemented the below, directly following the examples from the learn.microsoft.com. (I also added the same FileSavePicker code segment below to a small dummy winui-3 sand-box test app, but instead I put the code on the MainWindow's code-behind and it worked perfectly.) I need to get the FileSavePicker to work from a page instead of a MainWindow. Thank you all for your help so far.

I get this debug error:

enter image description here

I know the problem has to do with getting the MainWindow's HWND.

// Retrieve the window handle (HWND) of the current WinUI 3 window.
   var window = (MainWindow)Application.Current.MainWindow; (I tried this, but it did not work)

I get this error from the above line: enter image description here

(I tried this, but it did not work)

   var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(window); 

I get this error from the line above:

enter image description here

I don't know the correct syntax.

using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using System;
using System.Collections.Generic;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Provider;
    
namespace MetricReporting.Pages
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class pageReports : Page
    {
        public pageReports()
        {
            this.InitializeComponent();
        }

        private void ButtonBoltReport_Click(object sender, RoutedEventArgs e)
        {
            DisplayBOLTSaveDialog();
        }

        private async void DisplayBOLTSaveDialog()
        {

            FileSavePicker savePicker = new FileSavePicker();

            // Retrieve the window handle (HWND) of the current WinUI 3 window.
            var window = (MainWindow)Application.Current.MainWindow;
            var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(this);

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

            savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            // Dropdown of file types the user can save the file as
            savePicker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" });
            // Default file name if the user does not type one in or select a file to replace
            savePicker.SuggestedFileName = "New Document";

            StorageFile file = await savePicker.PickSaveFileAsync();
            if (file != null)
            {
                // Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
                CachedFileManager.DeferUpdates(file);
                // write to file
                await FileIO.WriteTextAsync(file, file.Name);
                // Let Windows know that we're finished changing the file so the other app can update the remote version of the file.
                // Completing updates may require Windows to ask for user input.
                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
                if (status == FileUpdateStatus.Complete)
                {
                    ReportStatus.Text = "File " + file.Name + " was saved.";
                }
                else
                {
                    ReportStatus.Text = "File " + file.Name + " couldn't be saved.";
                }
            }
            else
            {
                ReportStatus.Text = "Operation cancelled.";
            }
            
        }
    }
}

Solution

  • Change the modifier for the m_window field in App.xaml.cs:

    internal Window m_window;
    

    ...or better yet expose it through a property:

    public Window Window => m_window;
    

    Then you can access the window from the page like this:

    var window = (Application.Current as App)?.m_window as MainWindow; 
    

    or

    var window = (Application.Current as App)?.Window as MainWindow;