Reputation: 129
In a UWP App, when I try to retrieve the contents of the clipboard from within the OnNavigatedTo
method, the app crashes. Could someone help on this please?
Edit: It seems to crash only when it is launched by clicking on it from the start menu or by launching it by an another app. But when launched by Visual Studio, it works fine!
Upvotes: 0
Views: 292
Reputation: 5868
The debugging in visual studio is different from the start menu, you can try the Resuming and Suspending event when you run the app in vs, these event won't be triggered normally.
In addition, about the Clipboard, this document mentions you need to use Clipboard after CoreWindow is active. When the OnNavigatedTo event is triggered, the CoreWindow is not ready yet. You could try the following code and the Activated event will triggered many times, you can add some judgments in it.
public MainPage()
{
this.InitializeComponent();
CoreWindow window = CoreWindow.GetForCurrentThread();
window.Activated += Window_Activated;
}
private async void Window_Activated(CoreWindow sender, WindowActivatedEventArgs args)
{
var dataPackageView = Clipboard.GetContent();
var text = await dataPackageView.GetTextAsync();
}
Upvotes: 1
Reputation: 39082
There is no problem if you use Clipboard
in OnNavigatedTo
or even earlier (like in page constructor), but you must call Clipboard
APIs from the UI thread. Meaning the following will work:
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
var content = Clipboard.GetContent();
}
But the following will crash:
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
await Task.Run(() => { Clipboard.GetContent(); });
}
Please make sure, your code does indeed access the Clipboard
from the UI thread and it should work properly. To move to the UI thread, you can use the Dispatcher
(see for example this SO question)
Upvotes: 1