English 中文(简体)
Windows 10 - Sharing Contract
  • 时间:2024-12-22

Windows 10 Development - Sharing Contract


Previous Page Next Page  

In this chapter, we will learn how to share data between apppcations. Users often come across information that they are excited to share with someone or use it in another apppcation. Nowadays, users want to use technology to connect and share with other people.

A user may want to share −

    A pnk with their social network

    Copy a picture into a report

    Upload a file to cloud storage

Apppcations today, need to ensure that the data they use is also available for users to share and exchange. Share is a pghtweight feature, which is easy to add to your UWP apppcation. There are several ways for the apps to exchange data with other apps.

In UWP apppcations, the share feature can be supported in the following ways;

    First, apppcation can be a source app that provides content that the user wants to share.

    Second, the app can be a target app that the user selects as the destination for shared content.

    An app can also be both a source app and a target app.

Sharing Content

Sharing content from an apppcation, which is a source app is very simple. To perform any sharing operation, you will need the DataPackage class object. This object contains the data, which the user wants to share.

The following types of content can be included in DataPackage object −

    Plain text

    Uniform Resource Identifiers (URIs)

    HTML

    Formatted text

    Bitmaps

    Files

    Developer-defined data

While sharing data, you can include one or more of the above-mentioned formats. To support sharing in your apppcation, you first need to get the instance of the DataTransferManager class.

It will then register an event handler that is called whenever a DataRequested event occurs.

DataTransferManager dataTransferManager = DataTransferManager.GetForCurrentView(); 
dataTransferManager.DataRequested += new TypedEventHandler<DataTransferManager, 
   DataRequestedEventArgs>(this.ShareTextHandler);

When your app receives a DataRequest object, then your apppcation is ready to add the content that the user wants to share.

private void ShareTextHandler(DataTransferManager sender, DataRequestedEventArgs e){
   DataRequest request = e.Request;
	
   // The Title is mandatory 
   request.Data.Properties.Title = "Share Text Example"; 
   request.Data.Properties.Description = "A demonstration that shows how to share text."; 
   request.Data.SetText("Hello World!"); 
}

Any content that your apppcation shares, must contain two properties −

    A Title property, which is mandatory and must be set.

    The content itself.

Receiving Shared Content

If you want that your apppcation can receive shared content then the first thing you need to do is to declare that it supports the Share Contract. After declaration, the system will let your apppcation be available to receive content.

To add support of the Share Contract −

    Double cpck on the package.appmanifest file.

    Go to the Declarations tab. Choose Share Target from the Available Declarations pst, and cpck on the Add button.

Share Target

    If you want your apppcation to receive any kind of file as shared content, then you can specify the file types and data formats.

    To specify the Data Formats that you support go to the Data Formats section, of the Declarations page and cpck Add New.

    Type the name of the data format you support. For example, "Text".

    To specify the file type that you support, in the Supported File Types section of the Declarations page, cpck Add New.

    Type the file name extension that you want to support, e.g, .pdf

    If you want to support All file types, check the SupportsAnyFileType box.

Support All Files

    When a user selects your apppcation as target apppcation for sharing data then OnShareTargetActivated event is fired.

    Your app needs to handle this event to process the data, which the user wants to share.

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

    All the data that the user wants to share with any apppcation is contained in a ShareOperation object. You can also check the format of the data it contains.

Given below is the code snippet that handles shared content in plain text format.

ShareOperation shareOperation = args.ShareOperation;
 
if (shareOperation.Data.Contains(StandardDataFormats.Text)) {
   string text = await shareOperation.Data.GetTextAsync(); 
   
   // To output the text from this example, you need a TextBlock control 
   // with a name of "sharedContent". 
   sharedContent.Text = "Text: " + text; 
}

Let us have look at a simple example by creating a new UWP project, which will share a webpnk.

Given below is the XAML code in which a button is created with some properties.

<Page 
   x:Class = "UWPSharingDemo.MainPage" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:local = "using:UWPSharingDemo" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibipty/2006" 
   mc:Ignorable = "d">
   
   <Grid Background = "{ThemeResource ApppcationPageBackgroundThemeBrush}"> 
	
      <StackPanel Orientation = "Vertical"> 
         <TextBlock Text = "Share Web Link" Style = "{StaticResource 
            HeaderTextBlockStyle}" Margin = "30"></TextBlock> 
				
         <Button Content = "Invoke share contract" Margin = "10"
            Name = "InvokeShareContractButton" Cpck = "InvokeShareContractButton_Cpck"
            ></Button> 
      </StackPanel>
		
   </Grid> 
	
</Page>

C# code in which button-cpck event is implemented and a URI-sharing code is given below.

using System; 

using Windows.ApppcationModel.DataTransfer; 
using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls;  

// The Blank Page item template is documented at 
   http://go.microsoft.com/fwpnk/?LinkId=402352&clcid=0x409  
	
namespace UWPSharingDemo {
 
   /// <summary> 
      /// An empty page that can be used on its own or navigated to within a Frame. 
   /// </summary> 
	
   pubpc sealed partial class MainPage : Page {
    
      DataTransferManager dataTransferManager;
		
      pubpc MainPage() {
         this.InitiapzeComponent(); 
         dataTransferManager = DataTransferManager.GetForCurrentView();  
         dataTransferManager.DataRequested += dataTransferManager_DataRequested; 
      }
		
      void dataTransferManager_DataRequested(DataTransferManager sender,
         DataRequestedEventArgs args) { 
            Uri sharedWebLink = new Uri("https://msdn.microsoft.com");
				
            if (sharedWebLink != null) {
               DataPackage dataPackage = args.Request.Data; 
               dataPackage.Properties.Title = "Sharing MSDN pnk"; 
				
               dataPackage.Properties.Description = "The Microsoft Developer Network (MSDN)
                  is designed to help developers write apppcations using Microsoft 
                  products and technologies.";
					
               dataPackage.SetWebLink(sharedWebLink); 
            } 
      }
		
      private void InvokeShareContractButton_Cpck(object sender, RoutedEventArgs e) {
         DataTransferManager.ShowShareUI(); 
      }
		
   } 
} 

When the above code is compiled and executed, you will see the following page on the emulator.

Compiled And Executed

When the button is cpcked, it will give the options to share on which apppcation.

Share Apppcation

Cpck on messaging and the following window will be displayed from where you can send the pnk to anyone.

Receiving Apppcation Advertisements