winrt-xamldesktop-applicationwinui-3c++-winrt

FileOpenPicker returns memory error in WinUI 3


With reference to my previous question

I am exploring WinUI3 using C++ and struggling to find information and material on different community portals.

I developed a demo app which has a window and 2 pages. On one of the pages, I want to open a file picker.

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();
}

Error

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.

Solution

  • You have two problems

    so this should work:

    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();
    }