Windows Runtime APIs - Build Windows® 8 Apps with Microsoft® Visual C#® and Visual Basic® Step by Step (2013)

Build Windows® 8 Apps with Microsoft® Visual C#® and Visual Basic® Step by Step (2013)

Chapter 6. Windows Runtime APIs

After completing this chapter, you will be able to

§ Interact with Windows Runtime APIs from a Windows 8 app.

§ Use some of the available date, time, and file pickers.

§ Interact with the webcam to take photos and videos.

§ Implement the Share contract to share information between applications.

Chapter 5, covered the Windows Runtime (WinRT) architecture and the basic types, how to write code using the multilanguage features, and the concept of language projection. This chapter shows you how to interact with the user-related WinRT APIs such as File Picker and Webcam, and the APIs that you need to implement the Share contract.

Pickers

Windows 8 has two types of pickers. One has been in common use since the 1990s; it lets users choose something such as a date, a file, or a printer. This type of picker normally corresponds to user controls that are part of the framework or the programming environment. For example, ASP.NET provides the DatePicker Calendar Control, Windows Presentation Foundation (WPF) exposes a DatePicker control, and Windows Forms provided common dialog controls that let users pick files or printers from the operating system.

In Windows 8, you can find these kinds of controls as part of the Extensible Application Markup Language (XAML) framework or as part of the WinJS (Windows Library for JavaScript) library for HTML Windows 8 UI style apps (Windows Store app or simply Windows 8 app). To use them, you simply drag the controls from the Microsoft Visual Studio toolbox to the window editing surface or by coding their definition declaratively in XAML or HTML code.

The other types of pickers in Windows 8 are provided not by user controls, but rather via APIs exposed by WinRT. You can use them directly in your Windows 8 UI style applications or Windows 8 UI style class libraries without having to add any external references because they are part of the environment. For example, you can invoke these APIs to retrieve a file path for a document directly from code. It’s important to realize that the WinRT APIs are accessible from any Windows 8 UI style application—so you can access them using Microsoft C# or Microsoft Visual Basic code from a .NET Windows 8 UI style app, or using JavaScript code from HTML Windows 8 UI style apps.

A picker has its own user interface that adheres to the Windows 8 UI design language that you learned about in Chapter 2, and neither the layout nor the appearance can be modified from code; instead, your applications can customize only some settings.

To get a feel for how this works, in the next exercise you’ll start by coding the File Picker.

Using the File Picker

In this procedure, you will use the FileOpenPicker class, which allows a user to choose a file from the document library.

1. Create a new Application project. To do that, open Visual Studio 2012, and from the File menu, select New Project (the sequence can be File | New | Project for full-featured versions of Visual Studio). Choose Visual C# from the Templates tree and then Windows Store from the list of installed templates. Finally, choose the Blank App (XAML) project type from the list of available projects.

Select version 4.5 as the Microsoft .NET Framework target version for your new project (this is not necessary in the Visual Studio Express edition).

2. Name the new project FilePicker, and then choose a location on your file system without changing the default solution name. When you have finished, click OK.

As you saw in Chapter 3, the Windows Store application template provides a default page (MainPage.xaml), an application entry point in the App class (App.xaml.cs), a default application description and a declaration in the Package.appxmanifest file, as well as four default images representing logos and a splash screen.

image with no caption

3. Scroll down in the MainPage.xaml source code and insert a ListBox control and a Button control inside a StackPanel control, as illustrated in the bold lines of the following code excerpt.

4. <Page x:Class="FilePicker.MainPage"

5. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

6. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

7. xmlns:local="using:FilePicker"

8. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

9. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

10. mc:Ignorable="d">

11.

12. <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">

13. <StackPanel>

14. <Button Click="ChooseFiles_Click" Content="Choose Files" />

15. <ListBox x:Name="filesList" />

16. </StackPanel>

17. </Grid>

</Page>

The ListBox control will be filled with the file names chosen by the user through the FileOpenPicker picker; the button will simply fire the code to start the picker and bind the selected files in the ListBox.

18.Open the MainPage.xaml.cs file and add the method ChooseFiles_Click, which implements the event handler for the button. You can also double-click the button in the integrated development environment (IDE) designer. Add the async keyword to the method because pickers use the asynchronous pattern of .NET 4.5.

NOTE

You will learn all the details of this asynchronous technique in Chapter 8.

The code here represents the complete method definition:

private async void ChooseFiles_Click(object sender, RoutedEventArgs e)

{

}

19.Add the following code to the method to open the File Picker and retrieve the selected files.

20.var picker = new Windows.Storage.Pickers.FileOpenPicker();

21.picker.FileTypeFilter.Add("*");

22.

23.var files = await picker.PickMultipleFilesAsync();

24.

25.filesList.Items.Clear();

26.foreach (var file in files)

filesList.Items.Add(file.Name);

The first line of code creates an instance of the FileOpenPicker class and assigns it to the local variable named picker. Then the code adds a filter on the file type that the picker will show to the user (all files in this case).

The third line of code is the most important: it asks the FileOpenPicker class to let the user choose multiple files. It then awaits—waits for method completion in an asynchronous way, without blocking the current thread—the result. This new async pattern lets you write code that resembles synchronous code, simplifying coding and debugging. The async pattern eliminates the need to define callbacks and use the IAsyncResult interface.

When a user has chosen some files (or has clicked the Cancel button on the picker) the code continues by simply clearing and then filling ListBox with the selected files.

The complete code for MainPage.xaml.cs should look like the following.

using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using Windows.Foundation;

using Windows.Foundation.Collections;

using Windows.UI.Xaml;

using Windows.UI.Xaml.Controls;

using Windows.UI.Xaml.Controls.Primitives;

using Windows.UI.Xaml.Data;

using Windows.UI.Xaml.Input;

using Windows.UI.Xaml.Media;

using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/

fwlink/?LinkId=234238

namespace FilePicker

{

/// <summary>

/// An empty page that can be used on its own or navigated to within a Frame.

/// </summary>

public sealed partial class MainPage : Page

{

public MainPage()

{

this.InitializeComponent();

}

private async void ChooseFiles_Click(object sender, RoutedEventArgs e)

{

var picker = new Windows.Storage.Pickers.FileOpenPicker();

picker.FileTypeFilter.Add("*");

var files = await picker.PickMultipleFilesAsync();

filesList.Items.Clear();

foreach (var file in files)

filesList.Items.Add(file.Name);

}

/// <summary>

/// Invoked when this page is about to be displayed in a Frame.

/// </summary>

/// <param name="e">Event data that describes how this page was reached.

The Parameter

/// property is typically used to configure the page.</param>

protected override void OnNavigatedTo(NavigationEventArgs e)

{

}

}

}

Before running the project, remember that Visual Studio first deploys your application to Windows 8 and then starts it. Thus, after you run an app from Visual Studio, you will find the default app Tile on the Start screen. As you learned in Chapter 3, the default value for the Show Nameproperty in the application manifest is All Logos. Before moving on, choose the behavior you want for your app tile by opening the Package.appxmanifest file in the designer, and choosing the property Show Name.

NOTE

Please refer to Chapter 3, and Chapter 4, for a description of the structure of the manifest.

The following graphic shows the user interface for the main page of the application.

image with no caption

27.Click Choose Files and use the Windows 8 File Picker to select some files.

You can simply click or tap on a file to select or clear it. The following graphic shows the File Picker on the desktop with the Logo.png and SmallLogo.png files selected.

image with no caption

The top of the picker shows the user the selected directory, the applied sorting, and a link to select all the files in that folder. The content pane shows the available files where you enter selections by simply clicking or tapping on them. The bottom line of the picker shows the selected files, the Cancel button, and the Open button.

28.Select some files and then click Open.

image with no caption

As you have seen so far, the steps and the code to use a picker such as the File Picker are really simple.

You can define the text for the Open button using the CommitButtonText property, provide a default start location using the SuggestedStartLocation property, and use the PickSingleFileAysnc property if the user has to select a single file.

You also can change the viewing mode from list to thumbnail; this is the only allowed customization for the user interface. Add the following line of code just before the PickMultipleFileAsync call to modify the view mode.

private async void ChooseFiles_Click(object sender, RoutedEventArgs e)

{

var picker = new Windows.Storage.Pickers.FileOpenPicker();

picker.FileTypeFilter.Add("*");

picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;

var files = await picker.PickMultipleFilesAsync();

filesList.Items.Clear();

foreach (var file in files)

filesList.Items.Add(file.Name);

}

The last thing to notice before moving to the Webcam API is that you haven’t modified the manifest file to allow the access to the library. When you open the Capabilities tab on the Package.appxmanifest designer while in step 7, you may notice a Document Library property. It is not necessary to grant this capability, nor the Music Library or the Picture Library property, because they are not related to the FileOpenPicker.

Webcam

WinRT provides a very simple API to interact with the webcam from .NET, C++, or JavaScript code. As with other WinRT APIs, you do not need any references to class libraries to use the Webcam API. The .NET for Windows Store apps reference is added automatically when you create a new Windows Store App project in Visual Studio. If you don’t have a Webcam attached to your system, move on to the next example in the chapter because this example won’t be able to demonstrate the device capabilities for you.

Using the Webcam

In this procedure, you will start using the Webcam API to let the user take a photo (or a video) and return it to the Windows 8 UI style application.

1. Create a new Application project. To do that, open Visual Studio 2012, and from the File menu, select New Project. Choose Windows Store from the list of installed templates, and then choose Blank App (XAML) from the list of available projects.

2. Select version 4.5 as the .NET Framework target version for your new project.

3. Name the new project Webcam, and then choose a location on your file system and a solution name. When you’re finished, click OK.

4. Open the MainPage.xaml page and add a Button and an Image control. The button will fire the code to start the webcam, and the image will display the photo that the user will take. The following code shows the complete XAML code for MainPage.xaml. The lines in bold show what you need to add to the page.

5. <Page x:Class="Webcam.MainPage"

6. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

7. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

8. xmlns:local="using:Webcam"

9. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

10. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

11. mc:Ignorable="d">

12.

13. <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">

14. <StackPanel>

15. <Button Click="TakePhoto_Click" Content="Take Photo"/>

16. <Image x:Name="image" Height="800" />

17. </StackPanel>

18. </Grid>

19.

</Page>

20.Implement the event handler for the button click event using the following code as a reference:

21.using System;

22.using System.Collections.Generic;

23.using System.IO;

24.using System.Linq;

25.using Windows.Foundation;

26.using Windows.Foundation.Collections;

27.using Windows.Media.Capture;

28.using Windows.Storage;

29.using Windows.UI.Xaml;

30.using Windows.UI.Xaml.Controls;

31.using Windows.UI.Xaml.Controls.Primitives;

32.using Windows.UI.Xaml.Data;

33.using Windows.UI.Xaml.Input;

34.using Windows.UI.Xaml.Media;

35.using Windows.UI.Xaml.Media.Imaging;

36.using Windows.UI.Xaml.Navigation;

37.

38.// The Blank Page item template is documented at http://go.microsoft.com/

39.fwlink/?LinkId=234238

40.

41.namespace Webcam

42.{

43. /// <summary>

44. /// An empty page that can be used on its own or navigated to within a Frame.

45. /// </summary>

46.

47. public sealed partial class MainPage : Page

48. {

49. public MainPage()

50. {

51. this.InitializeComponent();

52. }

53.

54. private async void TakePhoto_Click(object sender, RoutedEventArgs e)

55. {

56. var camera = new CameraCaptureUI();

57. var img = await camera.CaptureFileAsync(CameraCaptureUIMode.Photo);

58. if (img != null)

59. {

60. var stream = await img.OpenAsync(FileAccessMode.Read);

61. var bitmap = new BitmapImage();

62. bitmap.SetSource(stream);

63. image.Source = bitmap;

64. }

65. }

66.

67. /// <summary>

68. /// Invoked when this page is about to be displayed in a Frame.

69. /// </summary>

70. /// <param name="e">Event data that describes how this page was reached.

71. /// The Parameter

72. /// property is typically used to configure the page.</param>

73.

74. protected override void OnNavigatedTo(NavigationEventArgs e)

75. {

76. }

77. }

}

The first line of code in the TakePhoto_Click method creates an instance of the CameraCaptureUI class and the second line waits for the completion of its method, CaptureFileAsync, which, as you can imagine, captures the stream using the async pattern, which prevents blocking the UI thread. The method accepts the CameraCaptureUIMode parameter, which can assume the value of Photo, Video, or PhotoOrVideo. In the presented example, the webcam will be activated to take a photo.

The CaptureFileAsync method returns an instance of the StorageFile WinRT class representing the captured stream as a file. This file can be opened as a stream using the OpenAsync method: the method returns an instance of IRandomAccessStream interface that can be used to set the source for a BitmapImage instance. Finally, the instance of the bitmap can be assigned to the Source property of the XAML Image control.

78.Modify the application manifest to set the Show Name property accordingly to your preferences, just as you did in the previous procedure, and then press F5.

If you click Take Photo, the webcam screen will occupy the entire screen, but you won’t be able to take a photo—in fact the default message is very clear and informs you that this app needs the user’s permission to use the camera. The reason is very simple: you cannot use the Webcam API without declaring the webcam capability in the application manifest. Obviously, if you have no camera attached to your PC, the application will first ask you to connect the device.

image with no caption

79.Stop the application, open the Package.appxmanifest file, go to the Capabilities tab, and select Webcam from the Capabilities list.

image with no caption

80.Click the application again, and then click or tap the Take Photo button. A message box (displayed in Windows 8 UI style) will ask you if this application can use the webcam.

image with no caption

This request is the standard mechanism that Windows 8 uses to ask the user for permission to use a specific application capability. In practice, the application needs to declare its capabilities in the manifest and the user has to provide permission to the application explicitly for each capability. If the user blocks a capability, the corresponding feature cannot be used. In the application you are building, the webcam shows a black screen in which the user cannot do anything but click Back to return to the application.

The system retains the user’s choice forever; however, users can remove a specific permission at any time for any application or restore a permission at any time, as you will see in the following steps.

81.Click the Block button in the screen represented in the previous image. The user can do nothing with the camera in this app.

82.Move the mouse to the lower-right corner to view the Charms and select Settings. A panel appears on the right of the screen with some settings in the lower section, such as the network joined by the system, the volume level, the language, and a button to turn off/sleep/restart the system.

83.In the upper section of the panel, you can see the application name, the user currently using the application, the version of the application, and the Permissions for the webcam. The following graphic shows the permissions for the Webcam App.

image with no caption

As you can see, the lower section of the pane presents the two capabilities requested in the application manifest: Internet Connection and Webcam.

84.By using the slider next to the Webcam item, grant the app permission to use the webcam. Immediately, you will be able to preview the image taken from the webcam in the remaining part of the screen.

image with no caption

You can turn the Webcam permission on or off at any time to verify how the permission mechanism works.

85.Tap or click the screen to take the photo and go to the confirmation screen, where you can crop the photo, accept it, or take a new one.

86.Accept the photo by clicking OK. The webcam dialog box will return the photo to the application, which, in turn, will display it on the main page.

image with no caption

The CameraCaptureUI class exposes some properties to define the settings to take photos and some properties to adjust the settings for taking videos. For instance, with the first, you can set the AllowCropping property to True or False, and you can set the format and the resolution for the image. With the latter, you can set the resolution for the video, the maximum duration, and the format.

If you want to record the audio as well, you need to specify the Microphone capability in the application manifest.

Sharing contracts

In Chapter 3, you implemented the Search contract feature to let the user search data inside your application.

A contract regulates the interaction between an application and the operating system. Every application that implements a Windows 8 contract can use the corresponding operating system feature.

The Sharing contract regulates data exchange between applications. Chapter 1, introduced and demonstrated the use of the Sharing contract to show how data can be passed from one application to another without direct communication. The operating system acts as a bridge between the source application and the target application, invoking the necessary APIs on both of them.

The source app needs to do the following:

§ Register itself with the Data Transfer Manager, which is the operating system component that manages the information exchange between the application and the target application.

§ Implement an event handler to reply to sharing requests. When the user chooses to share something, she activates the Share pane by using the Share charm. The operating system asks the source application to prepare the data package invoking an event on the source application; this corresponding event handler is the place where you prepare the data package. The source application can request a sharing operation directly from code without the user needing to use the Share charm.

The package specifies the type of resources it contains. The operating system lists all the target applications that can receive the same type of resources. For instance, if the source application shares images, the operating system will enumerate all the possible target applications that can receive images.

The target app needs to:

§ Define the sharing target declaration inside the application manifest.

§ Declare the types of resources that it can receive. This information is used by the operating system to create the list of applications that can receive the content shared by the source application.

§ Implement the sharing target activation, a special kind of application activation that receives the data package. This activation is requested by the operating system when the user chooses the application as the target for sharing operations.

§ Provide the page to be displayed in the pane filled with the information about the received data. For instance, a social application can display the received image and ask the user for a description and a tag before posting it to the social network.

§ Implement the logic to process the data. Following the preceding example, the application can post the image to Facebook. This process can be done in an asynchronous way if the operations are time-consuming.

§ Report the completion of the operation.

As you learned in Chapter 1, some native Windows 8 applications can be used as sources and others can be used as targets. For instance, the Windows 8 UI style version of Windows Internet Explorer can act as a source application, sharing the text the user has selected on a page to Mail, the preinstalled email application, which can receive the text and send it to a recipient.

Let’s see an example of using the native applications, and then you will implement a source application from scratch by using a very simple but effective application.

Using native applications

In this procedure, you start using the Windows 8 UI style version of Internet Explorer to share some information with Mail.

1. Open Internet Explorer from the Start screen. Be careful—do not use the classic Win32 version of Internet Explorer (which you can find on the classic taskbar, just in case you have activated the “old desktop” of Windows 8 from the Desktop tile).

2. Open any website (for example, http://www.devleap.com/) in the address bar. If you use that site, the text will appear in Italian. Select EN in the top menu.

3. Select some text on the home page and position the cursor in the lower-right corner of the screen (or press Windows+C) to open the Charm (or flip your finger from the right corner toward the center of the screen).

4. Choose Share from the menu or the Charm.

image with no caption

As you can see, the Windows 8 version of Internet Explorer has no window at all, nor a menu item or an address bar: it fills the entire surface of the screen. The Share pane appears on the right side of the screen.

You cannot customize the Share pane because it is an operating system component. On the top, it displays the information that comes from the source application, and immediately below that, it lists all the applications that are capable of receiving the content.

5. Select Mail to open the target application. The target application will receive the data package sent from Internet Explorer via the Data Transfer Manager. Mail will present the shared text with the hyperlink and show the Send Mail button. The target application page is displayed in the foreground, letting the user see the source application in the background. If you have not configured Mail in your system, the following graphic shows how this looks in action.

image with no caption

The target application is responsible for presenting the content on the Share pane and informing users about the operations available for that content. This is a good example of a target application because Mail receives the data package and processes it, sending the resulting email to the target recipients.

Now that you have seen the complete flow, you’ll implement a sharing source application of your own from scratch.

Implement a source application

In this procedure, you will implement a simple source application that can share textual content.

1. Create a new Application project. To do that, open Visual Studio 2012, and from the File menu, select New Project. Choose Windows Store from the list of installed templates, and then choose Blank App (XAML) from the list of available projects.

2. Select version 4.5 as the .NET Framework target version for your new project.

3. Name the new project SharingSource, and then choose a location on your file system and a solution name. When you’re finished, click OK.

4. Open the MainPage.xaml page and add a ListView control, using the following code as a guide:

5. <Page x:Class="SharingSource.MainPage"

6. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

7. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

8. xmlns:local="using:SharingSource"

9. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

10. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

11. mc:Ignorable="d">

12.

13. <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">

14. <ListView x:Name="list" DisplayMemberPath="FullName"

15. SelectedValuePath="FullName" />

16. </Grid>

</Page>

17.Fill the ListView control with some people’s names using code similar to the following in the constructor of the MainPage class:

18.public sealed partial class MainPage : Page

19.{

20. public MainPage()

21. {

22. this.InitializeComponent();

23.

24. list.ItemsSource = new List<object>()

25. {

26. new { FullName = "Roberto Brunetti " },

27. new { FullName = "Paolo Pialorsi" },

28. new { FullName = "Marco Russo" },

29. new { FullName = "Luca Regnicoli" },

30. new { FullName = "Vanni Boncinelli" },

31. new { FullName = "Guido Zambarda" },

32. new { FullName = "Katia Egiziano" },

33. new { FullName = "Jessica Faustinelli" }

34. };

}

35.Test the application to verify that you can see the names on the page and that you can select one of them.

36.Add the code to respond to the sharing event that the operating system will fire on the applications using the DataTransferManager WinRT class. Use this code inside the constructor of the class, just below the InitializeComponent method call:

37.DataTransferManager.GetForCurrentView().DataRequested +=

38.

39. new TypedEventHandler<DataTransferManager,

DataRequestedEventArgs>(MainPage_DataRequested);

40.Add the using statement to the namespace that provides the DataTransferManager class as follows:

using Windows.ApplicationModel.DataTransfer;

41.Implement the MainPage_DataRequested method using the following code:

42.void MainPage_DataRequested(DataTransferManager sender, DataRequestedEventArgs

43. args)

44.{

45. args.Request.Data.Properties.Title = "DevLeap Sharing";

46. if (list.SelectedItem != null)

47. {

48. args.Request.Data.Properties.Description = "DevLeap is sharing his

49. crew member " + list.SelectedValue.ToString();

50. args.Request.Data.SetText(list.SelectedValue.ToString());

51. }

52. else

53. {

54. args.Request.FailWithDisplayText("You have selected no one");

55. }

}

The method sets the Request property of the received event arguments: it represents the data package to pass to the Data Transfer Manager that, in turn, sends it to the target application.

The first line sets the Title property of the data package. If no item was selected in the list, then the package shows text indicating a failure in data sharing because there is nothing to share.

If a name is selected, the source application sets the description of the data package and, more importantly, uses the SetText method to indicate that the package contains a set of characters and defines the desired text; the first one is very important because the Share pane will list all the registered applications that can receive text.

You can use SetBitmap, SetHtml, SetStorageItems, SetUri, SetRtf, and some other self-explaining methods.

56.Run the application, open the Charm, and choose Share.

image with no caption

The message “There’s nothing to share right now” is the default text that the Share pane shows the user when the source application uses the FailWithDisplayText method. The text provided by the source application is shown immediately below the default error message.

57.Select the first name from the list and share the content again. Now the Share pane shows several applications and presents the text provided by the code you implemented.

image with no caption

58.Select Mail.

image with no caption

You also can activate the sharing operation from the code of the source application using the ShowSendUI or the ShowShareUI static methods of the DataTransferManager class.

Implementing a target application

In this procedure, you will implement a simple target application that displays the textual content shared by some other application. Remember that any app that can share textual content will be able to share it with the application that you are about to implement in this procedure; this is because the Sharing contract regulates the data exchange between applications so they don’t need to know anything about each other in advance. You will implement an HTML Windows 8 UI style application to see how to interact with WinRT APIs from JavaScript and how to create a simple HTML page to show the text shared by some other applications. It’s important to note that you could do the same thing using XAML and C# or Visual Basic.

1. Create a new Application project. To do that, open Visual Studio 2012, and from the File menu, select New Project. Choose JavaScript from the Templates tree and then Windows Store from the list of installed templates. Then choose Blank App from the list of available projects.

2. Name the new project SharingTarget, and then choose a location on your file system and a solution name. When you’re finished, click OK. Use the following graphic as a reference.

image with no caption

3. Open the manifest by double-clicking the Package.appxmanifest file and selecting the Declaration tab.

4. Select Share Target from the list of Available Declarations and click Add. This setting is necessary for this application to be considered a share target.

5. Click the Add New button in the Data Formats pane and type Text in the Data Format text box. This setting tells the Share pane that this application supports only text.

6. Leave other settings at their default values and save the manifest. You must have a manifest configured like the one illustrated in the following graphic.

image with no caption

7. Deploy the application to test it. You have not provided a user interface yet, but the steps you have completed so far will suffice for the application to be listed as a target when you try to share text from other applications.

8. Open Windows 8 Internet Explorer from the Start screen. You may see the home page of the site used in the previous procedure. If not, type an address (such as http://www.devleap.com/) in the address bar.

9. Select the first line of text and activate the Share pane.

10.Verify that the application (SharingTarget if you have carefully followed this procedure) will appear in the list.

image with no caption

If you select your application in the Share pane, you will see a blank page (with the default “content goes here” text) because you have not implemented the page yet. It’s time to do that.

Implementing a result page

In this procedure, you will develop an HTML Windows 8 UI style application. The page that displays when the user selects this application as the target for a sharing operation will be implemented in HTML5, using the WinRT APIs from JavaScript.

It is beyond the scope of this book to analyze or explain in detail how to build an HTML Windows 8 UI style application, but for this exercise, you will use the simplest way to build this page.

1. Replace the default body content (the paragraph) with an H1, H2, and H3 HTML tag inside the body of the default page as follows:

2. <body>

3. <h1 />

4. <h2 />

5. <h3 />

</body>

The manifest references the default page, which represents the starting point for the app.

6. Open the default.js file, which is available in the js folder of the project, and add the following variable declaration, just after the app variable declaration:

var shareOperation;

7. This variable will be used in the next steps to hold information about the data shared.

8. Within the same default.js file, add a script excerpt in the app.onactivated event handler. The code excerpt implements the activation of the application by using the WinRT environment, in case of a request for sharing contents. The following code illustrates how the app.onactivatedevent handler should be after modification.

9. app.onactivated = function (args) {

10.if (args.detail.kind === activation.ActivationKind.launch) {

11. if (args.detail.previousExecutionState !==

12. activation.ApplicationExecutionState.terminated) {

13. // TODO: This application has been newly launched. Initialize

14. // your application here.

15. } else {

16. // TODO: This application has been reactivated from suspension.

17. // Restore application state here.

18. }

19. args.setPromise(WinJS.UI.processAll());

20.} else if (args.detail.kind ==

21. Windows.ApplicationModel.Activation.ActivationKind.shareTarget) {

22. shareOperation = args.detail.shareOperation;

23.

24.

25. if (shareOperation.data.contains(

26. Windows.ApplicationModel.DataTransfer.StandardDataFormats.text)) {

27. document.querySelector('h1').textContent =

28. shareOperation.data.properties.title;

29. document.querySelector('h2').textContent =

30. shareOperation.data.properties.description;

31.

32.

33. shareOperation.data.getTextAsync().then(function (text) {

34. if (text !== null) {

35. document.querySelector('h3').textContent = text;

36. }

37. });

38. }

39.}

};

You can see the inserted code in bold. App activation can occur via the application tile on the Start screen or—as in the page you are building—when the user selects an application as a search target. The just added else if statement in the onactivated event handler tests this condition by analyzing the kind property of the detail of the received event arguments.

If the condition is met, the code fills the HTML header elements with the properties of the received Data Package. In the source application that you built in the previous procedures, you filled the same properties during the share operation.

40.Deploy the application again and test it as a share target from Internet Explorer as you did in steps 8–10 of the preceding procedure. You do not need to open the share target application, as you did not have to open Mail in the previous example. The system activates the share target automatically as you will see during the sharing operation in the next step.

41.Open the Share App that you built in this chapter from the Start screen, select a name from the list, and activate the Sharing charm as you learned (swipe your finger from the right towards the center of the screen, and then choose Share). When the Share pane opens, choose SharingTarget as the target application for the sharing operation and you will see the page that you built filled with the shared information.

image with no caption

Sharing is a powerful technique for sending and receiving information to and from applications using a common contract defined by WinRT.

Summary

In this chapter, you saw some WinRT APIs at work. You started with the FileOpenPicker class, which lets the user choose and send file information to the calling application. Next, you implemented a simple application using the CameraCaptureUI class to take and retrieve photos from the webcam. The last example features two different applications: the first one lets the user choose a person from a list and share his or her full name to other applications. The second application represents the target application and was built using HTML and JavaScript. Every WinRT API can be called from any language.

Quick reference

To

Do this

Use APIs that access the system

Specify the corresponding capabilities in the application manifest.

Block or allow capabilities for one application

Open the settings pane for the application and set the slider for every capability accordingly.

Interact with the webcam

Specify the Web capability and use the CameraCaptureUI class settings, the video and photo attributes, and then the CaptureFileAsync method.

Create a source application for sharing content

Use the DataTransferManager to create the data package and respond to the sharing event.

Receive content from other applications

Use the Share Target declaration in the application manifest and intercept the activation for the sharing operation.