FileOpenPicker 在 WinUI 3 中返回内存错误

问题描述 投票:0回答:1

参考我的之前的问题

我正在使用 C++ 探索 WinUI3,并努力在不同的社区门户上查找信息和材料。

我开发了一个演示应用程序,有一个窗口和 2 个页面。在其中一页上,我想打开一个文件选择器。

Tab1Page.xaml.cpp

void winrt::App1::implementation::Tab1Page::Button_Click(winrt::Windows::Foundation::IInspectable const& sender, winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e)
{
    OutputTextBlock().Text(OutputTextBlock().Text() + L"Button Clicked\n");

    auto hwnd = GetProcessFirstWindowHandle();

    auto picker = winrt::Windows::Storage::Pickers::FileOpenPicker();
    //Initialize the folder picker with the window handle(HWND).
    auto initializeWithWindow { picker.as<::IInitializeWithWindow>()
    };
    initializeWithWindow->Initialize(hwnd);
    picker.SuggestedStartLocation(winrt::Windows::Storage::Pickers::PickerLocationId::Desktop);
    winrt::Windows::Storage::StorageFile file = picker.PickSingleFileAsync().get();
}

错误

winrt::Windows::Storage::StorageFile file = picker.PickSingleFileAsync().get();`

Exception thrown at 0x00007FF9A92706BC in App1.exe: Microsoft C++ exception: winrt::hresult_error at memory location 0x0000007EA60F9B88.
winrt-xaml desktop-application winui-3 c++-winrt
1个回答
1
投票

你有两个问题

  • 正如您在调试输出中看到的那样,FileTypeFilters 集合中必须至少有一项
  • 您的代码必须
  • 在 UI 线程上运行
所以这应该有效:

Windows::Foundation::IAsyncAction winrt::App1::implementation::Tab1Page::Button_Click(IInspectable const& sender, RoutedEventArgs const& args) { auto hwnd = GetFirstProcessWindowHandle(); auto picker = winrt::Windows::Storage::Pickers::FileOpenPicker(); picker.FileTypeFilter().Append(L"*"); auto initializeWithWindow{ picker.as<IInitializeWithWindow>() }; initializeWithWindow->Initialize(hwnd); picker.SuggestedStartLocation(winrt::Windows::Storage::Pickers::PickerLocationId::Desktop); auto file = co_await picker.PickSingleFileAsync(); }
    
© www.soinside.com 2019 - 2024. All rights reserved.