Partager via


How to receive a link (XAML)

[This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation]

Links are a common form of data that users want to share. Sometimes the user shares a link directly (such as from an article on a website). Supporting links is also helpful as a secondary option when users are sharing HTML or content that might be available online.

This topic shows how to receive a single link that's being shared from a source app.

What you need to know

Technologies

Prerequisites

  • You should be familiar with Visual Studio and its associated templates.
  • You should be familiar with C# development.

Instructions

Step 1: Support the Share contract

Before your app can receive shared content, you have to declare that it supports the Share contract. This contract lets the system know that your app is available to receive content. If you're using a Visual Studio template to create your app, here's how you support the Share contract:

  1. Open the manifest file. It should be called something like package.appxmanifest.
  2. Open the Declarations tab.
  3. Choose Share Target from the Available Declarations list.

To support links, you need to specify that your app supports the WebLink format.

To specify that you support WebLink as a data format:

  1. Open the manifest file.
  2. In the Data Formats section, click Add New.
  3. Type weblink.

Step 3: Add the necessary namespaces

For a target app, you'll need the Windows.ApplicationModel.Activation, Windows.ApplicationModel.DataTransfer, and Windows.ApplicationModel.DataTransfer.ShareTarget namespaces:

using Windows.ApplicationModel.Activation;
using Windows.ApplicationModel.DataTransfer;
using Windows.ApplicationModel.DataTransfer.ShareTarget;

Step 4: Handling share activation

When a user selects your app to share content, the system activates your app by calling the app's Application.OnShareTargetActivated method. You need to override this method to get the content that a user wants to share.

protected override async void OnShareTargetActivated(ShareTargetActivatedEventArgs args)
{
    // Code to handle activation goes here. 
}

Step 5: Get the ShareOperation object.

The ShareOperation object contains all the data that your app needs, to get the content that a user wants to share.

ShareOperation shareOperation = args.ShareOperation;

The ShareOperation object contains a DataPackageView object. This object is essentially a read-only version of the DataPackage object that the source app used to create the data. Use this object to see if the content being shared is available in text format.

if (shareOperation.Data.Contains(StandardDataFormats.WebLink))
{
    // Code to process the URI goes here.
}

Even if your app supports only links, you should add a statement similar to the preceding code. It makes it easier to support other data types and file formats later if you choose.

To get the WebLink, call the DataPackageView.GetWebLinkAsync method.

ShareOperation shareOperation = args.ShareOperation;
if (shareOperation.Data.Contains(StandardDataFormats.WebLink))
{
    Uri uri = await shareOperation.Data.GetWebLinkAsync();
    if (uri != null)
    {
        // To output text from this example, you need a TextBlock control
        // with a name of "contentValue". 
        contentValue.Text = "Uri: " + uri.AbsoluteUri + Environment.NewLine;
    }
}

Of course, what you do with the link depends on your app.

Step 8: Call ReportCompleted.

After your app finishes processing the content that the user wants to share, call ReportCompleted so the system knows your app is no longer needed.

shareOperation.ReportCompleted();

Note  If you're going to test the code in this section, we recommend that you do not immediately add the code that calls ReportCompleted. This is because ReportCompleted causes the system to close your app, which prevents the test from proceeding. When you move your code into production, make sure you add the call to ReportCompleted.

 

Remarks

The best way to see how an app can receive text as part of sharing is by checking out our code sample. However, the following example should also give you a good idea.

Example

protected override async void OnShareTargetActivated(ShareTargetActivatedEventArgs args)
{
    ShareOperation shareOperation = args.ShareOperation;
    if (shareOperation.Data.Contains(StandardDataFormats.WebLink))
    {
        Uri uri = await shareOperation.Data.GetWebLinkAsync();
        if (uri != null) 
        {
            // To output the text from this example, you need a TextBlock control
            // with a name of "contentValue".
            contentValue.Text = "Uri: " + uri.AbsoluteUri + Environment.NewLine;
        }
    }
   
    shareOperation.ReportCompleted();
}


protected override void OnNavigatedTo(NavigationEventArgs e)
{
    // It is recommended to only retrieve the ShareOperation object in the activation handler, 
    // return as quickly as possible, and retrieve all data from the share target asynchronously.

    this.shareOperation = (ShareOperation)e.Parameter;

    var unused = Task.Factory.StartNew(async () =>
    {
        // Retrieve the data package properties.
        this.sharedDataTitle = this.shareOperation.Data.Properties.Title;
        this.sharedDataDescription = this.shareOperation.Data.Properties.Description;
        this.sharedThumbnailStreamRef = this.shareOperation.Data.Properties.Thumbnail;
        this.shareQuickLinkId = this.shareOperation.QuickLinkId;

        // Retrieve the data package content.
        if (this.shareOperation.Data.Contains(StandardDataFormats.WebLink))
        {
            // The GetWebLinkAsync(), GetTextAsync(), GetStorageItemsAsync(), etc. APIs will throw if there was an error retrieving the data from the source app.
            // In this sample, we just display the error. It is recommended that a share target app handles these in a way appropriate for that particular app.
            try
            {
                this.sharedUri = await this.shareOperation.Data.GetWebLinkAsync();
            }
            catch (Exception ex)
            {
                NotifyUserBackgroundThread("Failed GetWebLinkAsync - " + ex.Message, NotifyType.ErrorMessage);
            }
        }

        // In this sample, we just display the shared data content.

        // Get back to the UI thread using the dispatcher.
        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
        {
            DataPackageTitle.Text = this.sharedDataTitle;
            DataPackageDescription.Text = this.sharedDataDescription;

            if (!String.IsNullOrEmpty(this.shareOperation.QuickLinkId))
            {
                SelectedQuickLinkId.Text = this.shareQuickLinkId;
            }

            if (this.sharedThumbnailStreamRef != null)
            {
                IRandomAccessStreamWithContentType thumbnailStream = 
                        await this.sharedThumbnailStreamRef.OpenReadAsync();
                BitmapImage bitmapImage = new BitmapImage();
                bitmapImage.SetSource(thumbnailStream);
                ThumbnailHolder.Source = bitmapImage;
                ThumbnailArea.Visibility = Visibility.Visible;
            }
            if (this.sharedUri != null)
            {
                AddContentValue("Uri: ", this.sharedUri.AbsoluteUri);
            }
        });
    });
}

Sharing content target app sample

Sharing and exchanging data

How to receive HTML

How to receive text

Quickstart: Receiving shared content

DataPackage

Windows.ApplicationModel.DataTransfer

Windows.ApplicationModel.DataTransfer.Share

Guidelines for debugging target apps