XAML 在WinUI 3 C#中使用HWND for Pages

epggiuax  于 12个月前  发布在  C#
关注(0)|答案(1)|浏览(135)

我已经连续第三天尝试初始化filepicker了。在空项目中,我能够在窗口中实现窗口句柄,但在我的项目中页面是突出的。如何实现页面的窗口句柄?
这是我的代码

public sealed partial class uploadingUVPage : Page
    {
        public uploadingUVPage()
        {
            this.InitializeComponent();
        }

        private async void PickAFileButton_Click(object sender, RoutedEventArgs e)
        {
            // Create a file picker
            var openPicker = new Windows.Storage.Pickers.FileOpenPicker();

            // Retrieve the window handle (HWND) of the current WinUI 3 window.
            IntPtr hWnd = WindowNative.GetWindowHandle(this);

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

            // Set options for your file picker
            openPicker.ViewMode = PickerViewMode.Thumbnail;
            openPicker.FileTypeFilter.Add("*");

            // Open the picker for the user to pick a file
            var file = await openPicker.PickSingleFileAsync();
            if (file != null)
            {
                PickAFileOutputTextBlock.Text = "Picked file: " + file.Name;
            }
            else
            {
                PickAFileOutputTextBlock.Text = "Operation cancelled.";

            }
        }
    }

首先我尝试了从winui3画廊的初始化

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

但后来我把它换成

IntPtr hWnd = WindowNative.GetWindowHandle(this);
tgabmvqs

tgabmvqs1#

您需要将Window的示例传递给GetWindowHandle
但在这一行,

上传UVPage.cs

// Retrieve the window handle (HWND) of the current WinUI 3 window.
IntPtr hWnd = WindowNative.GetWindowHandle(this);

你正在传递this,它是uploadingUVPage的示例。
您需要做的是获取Window的示例,即在创建普通WinUI 3项目时在App.xaml.cs中示例化的MainWindow
一种方法是:

App.xaml.cs

public partial class App : Application
{
    public static Window Window { get; } = new MainWindow();

    public App()
    {
        this.InitializeComponent();
    }

    protected override void OnLaunched(LaunchActivatedEventArgs args)
    {
        Window.Activate();
    }
}

然后:

上传UVPage.cs

// Retrieve the window handle (HWND) of the current WinUI 3 window.
IntPtr hWnd = WindowNative.GetWindowHandle(App.Window);

相关问题