mans
mans

Reputation: 18228

how to wait for FileOpenPicker in UWP/WinRT to display and get the selected file from user? (C++ code)

I am new in UWP/WinRT!

I have this code:

void MainPage::processButton_Click(winrt::Windows::Foundation::IInspectable const& sender, winrt::Windows::UI::Xaml::RoutedEventArgs const& e)
    {
        winrt::Windows::Storage::Pickers::FileOpenPicker picker;
        picker.ViewMode(winrt::Windows::Storage::Pickers::PickerViewMode::Thumbnail);
        picker.FileTypeFilter().Append(L".mp4");
        auto filename= picker.PickSingleFileAsync().GetResults();           
       
    }

When I run this code, I am getting this error during run time:

A breakpoint instruction (__debugbreak() statement or a similar call) was executed in test.exe.

Changing the code to this one:

void MainPage::processButton_Click(winrt::Windows::Foundation::IInspectable const& sender, winrt::Windows::UI::Xaml::RoutedEventArgs const& e)
    {
        winrt::Windows::Storage::Pickers::FileOpenPicker picker;
        picker.ViewMode(winrt::Windows::Storage::Pickers::PickerViewMode::Thumbnail);
        picker.FileTypeFilter().Append(L".mp4");
        auto filename= picker.PickSingleFileAsync().GetResults();
        
    }

Generate the same error.

How can I wait for a picker to finish its job and return a file that I can open in my C++ UWp/WinRT?

Upvotes: 0

Views: 272

Answers (1)

IInspectable
IInspectable

Reputation: 51511

The diagnostic you get is raised when you attempt to call GetResults on an IAsyncOperation that hasn't run to completion.

To get around this you'll want to asynchronously wait for the operation to complete. The most direct way is to use a coroutine. Concurrency and asynchronous operations with C++/WinRT has all the information you need.

You can apply this to your code by changing it to the following:

IAsyncAction MainPage::processButton_Click(IInspectable sender, RoutedEventArgs e)
{
    winrt::Windows::Storage::Pickers::FileOpenPicker picker;
    picker.ViewMode(winrt::Windows::Storage::Pickers::PickerViewMode::Thumbnail);
    picker.FileTypeFilter().Append(L".mp4");
    auto filename = co_await picker.PickSingleFileAsync();
}

Make sure to change the signature from taking references to receiving arguments by value. If you don't things will break in ways that are entirely hard to diagnose.

Upvotes: 1

Related Questions