Search code examples
c#uwpsharescreen-capture

How to register a UWP app as share recipient for camera snapshot


In Windows 10, when I hit e.g. SHIFT + WIN + S I can take a screenshot of my screen. In other cases I have my webcam that can take a picture, and so on. All those scenarios have the feature to "Share" the captured image to another app, e.g. Mail, OneNote, etc.

I would like to register my own UWP app to be the recipient of such Share, so that the user can manipulate the captured image in my UWP app.

Is there a way to configure my UWP app to do this?


Solution

  • Is there a way to configure my UWP app to do this?

    Yes, you could make your UWP app a receiver when you want to share some content from other apps.

    1. Declare your app as a share target. Open the manifest file. Find the Declarations tab, then choose Share Target from the Available Declarations list, and then select Add.

    2. Set the file types and formats based on your requirements in the Declarations. For example, if you need to receive a screenshot, you will need to add Bitmap in the Data format.

    3. Handle share activation in the App.Xaml.cs by handling the Application.OnShareTargetActivated event.

    I've made a simple test about this and you could refer to it. For more information about this, you could also check this document: Receive data

    Manifest file:

    enter image description here

    App.xaml.cs:

       protected override async void OnShareTargetActivated(ShareTargetActivatedEventArgs args)
        {
            ShareOperation shareOperation = args.ShareOperation;
            if (shareOperation.Data.Contains(StandardDataFormats.Bitmap))
            {
                 var imageStream = await shareOperation.Data.GetBitmapAsync();
    
                Frame rootFrame = Window.Current.Content as Frame;
    
                if (rootFrame == null)
                {
                    // Create a Frame to act as the navigation context and navigate to the first page
                    rootFrame = new Frame();
                    Window.Current.Content = rootFrame;
                }
    
                rootFrame.Navigate(typeof(ShareImagePage), imageStream);
    
                Window.Current.Activate();
            }
        }
    

    ShareImagePage:

     protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (e.Content != null)
            {
                IRandomAccessStreamReference imageReceived = null;
    
                imageReceived = e.Parameter as IRandomAccessStreamReference;
    
                using (var imageStream = await imageReceived.OpenReadAsync())
                {
                    var bitmapImage = new BitmapImage();
                    bitmapImage.SetSource(imageStream);
                    imgImage.Source = bitmapImage;
                }
            }
    
        }