Search code examples
c#xamluwpclipboardricheditbox

UWP C#. Intercept Copy command in RichEditBox


I'm developing a UWP app using Xaml and C#. Here is my problem.

My app uses a RichEditBox to process text. Every time the user close the app the clipboard content copied from within the app is cleared. To solve this issue I red you have to use Clipboard.Flush(). OK, but what happens when I'm not controlling the copy process. If the user press Crtl+C or use the RichEditBox context menu to Copy the text, I can't intercept that action. The other workaround is to use Clipboard.ContentChanged. But when I use it for this situation, for some reason, the method creates an infinite loop. Please, any help.


Solution

  • Every time the user close the app the clipboard content copied from within the app is cleared.

    By testing on my side, if using Clipboard.SetContent() method to copy content to clipboard, the content will not be cleared by default after app closed. But if using Ctrl+C or right click the context menu, as you mentioned, the content copy to clipboard will be cleared.

    The other workaround is to use Clipboard.ContentChanged. But when I use it for this situation, for some reason, the method creates an infinite loop

    To resolve this, Clipboard.ContentChanged event handle do help since both Ctrl+C or right click the context menu will trigger this event. The loop is caused by you are trying to SetContent or Flush that cause ContentChanged trigger again. You could try to remove the event subscription before you are invoking these methods. For example:

    private async void Clipboard_ContentChanged(object sender, object e)
    {
        Clipboard.ContentChanged -= Clipboard_ContentChanged;
        DataPackageView clipboardContent = Windows.ApplicationModel.DataTransfer.Clipboard.GetContent();
        var dataPackage = new DataPackage();
        dataPackage.SetText(await clipboardContent.GetTextAsync());
        Clipboard.SetContent(dataPackage);
        Clipboard.ContentChanged += Clipboard_ContentChanged;
       // Clipboard.Flush();
    }
    

    Create an empty UWP, add a RichEditBox, copy content from it using Ctrl+C and close the app

    Actually, you could re-set the content to clipboard in the app's suspending event which will be triggered before the app was closed.

     private async void OnSuspending(object sender, SuspendingEventArgs e)
     {
         var deferral = e.SuspendingOperation.GetDeferral();
         //TODO: Save application state and stop any background activity 
         DataPackageView clipboardContent = Windows.ApplicationModel.DataTransfer.Clipboard.GetContent();
         var dataPackage = new DataPackage();
         dataPackage.SetText(await clipboardContent.GetTextAsync());
         Clipboard.SetContent(dataPackage);          
      // Clipboard.Flush(); 
         deferral.Complete();
     }