Quickstart: Register an app for AutoPlay content (XAML)

You can register apps as options for AutoPlay content events. AutoPlay content events are raised when a volume device such as a camera memory card, thumb drive, or DVD is inserted into the PC.

Roadmap: How does this topic relate to others? See:

Here we show how to identify your app as an AutoPlay option when a volume device from a camera is inserted.

Objective: Create an app to handle an AutoPlay content event.

Prerequisites

Microsoft Visual Studio

Instructions

1. Create a new project and add AutoPlay declarations

  1. Open Visual Studio and select New Project from the File menu. In the Visual C# section, select Windows Store. Name the app AutoPlayDisplayOrCopyImages and click OK.

  2. Open the Package.appxmanifest file and select the Capabilities tab. Select the Removable Storage and Pictures Library capabilities. This gives the app access to removable storage devices for camera memory, and access to local pictures.

  3. In the manifest file, select the Declarations tab. In the Available Declarations drop-down list, select AutoPlay Content and click Add. Select the new AutoPlay Content item that was added to the Supported Declarations list.

  4. An AutoPlay Content declaration identifies your app as an option when AutoPlay raises a content event. The event is based on the content of a volume device such as a DVD or a thumb drive. AutoPlay examines the content of the volume device and determines which content event to raise. If the root of the volume contains a DCIM, AVCHD, or PRIVATE\ACHD folder, or if a user has enabled Choose what to do with each type of media in the AutoPlay Control Panel and pictures are found in the root of the volume, then AutoPlay raises the ShowPicturesOnArrival event.

    In the Launch Actions section, enter the following values for the first launch action.

Setting Value
Verb show
Action Display Name Show Pictures
Content Event ShowPicturesOnArrival
  The **Action Display Name** setting identifies the string that AutoPlay displays for your app. The **Verb** setting identifies a value that is passed to your app for the selected option. You can specify multiple launch actions for an AutoPlay event and use the **Verb** setting to determine which option a user has selected for your app. You can tell which option the user selected by checking the **verb** property of the startup event arguments passed to your app. You can use any value for the **Verb** setting except, **open**, which is reserved.
  1. In the Launch Actions section for the AutoPlay Content item, click Add New to add a second launch action. Enter the following values for the second launch action.
Setting Value
Verb copy
Action Display Name Copy Pictures Into Library
Content Event ShowPicturesOnArrival
 
  1. In the Available Declarations drop-down list, select File Type Associations and click Add. In the Properties of the new File Type Associations declaration, set the Display Name field to AutoPlay Copy or Show Images and the Name field to image_association1. In the Supported File Types section, click Add New. Set the File Type field to .jpg. In the Supported File Types section, set the File Type field of the new file association to .png. For content events, AutoPlay filters out any file types that are not explicitly associated with your app.

  2. Save and close the manifest file.

2. Add XAML UI

  • Open the MainPage.xaml file and add the following XAML to the default <Grid> section.

    <TextBlock FontSize="18">File List</TextBlock>
    <TextBlock x:Name="FilesBlock" HorizontalAlignment="Left" TextWrapping="Wrap" 
               VerticalAlignment="Top" Margin="0,20,0,0" Height="280" Width="240" />
    <Canvas x:Name="FilesCanvas" HorizontalAlignment="Left" VerticalAlignment="Top" 
            Margin="260,20,0,0" Height="280" Width="100"/>
    

3. Add initialization code

The code in this step checks the verb value in the Verb property, which is one of the startup arguments passed to the app during the OnFileActivated event. The code then calls a method related to the option that the user selected. For the camera memory event, AutoPlay passes the root folder of the camera storage to the app. You can retrieve this folder from the first element of the Files property.

  1. Open the App.xaml.cs or App.xaml.vb file and add the following code to the App class.

    protected override void OnFileActivated(FileActivatedEventArgs args)
    {
        if (args.Verb == "show")
        {
            Frame rootFrame = (Frame)Window.Current.Content;
            MainPage page = (MainPage)rootFrame.Content;
    
            // Call DisplayImages with root folder from camera storage.
            page.DisplayImages((Windows.Storage.StorageFolder)args.Files[0]);
        }
    
        if (args.Verb == "copy")
        {
            Frame rootFrame = (Frame)Window.Current.Content;
            MainPage page = (MainPage)rootFrame.Content;
    
            // Call CopyImages with root folder from camera storage.
            page.CopyImages((Windows.Storage.StorageFolder)args.Files[0]);
        }
    
        base.OnFileActivated(args);
    }
    
    Protected Overrides Sub OnFileActivated(args As FileActivatedEventArgs)
        If args.Verb = "show" Then
            Dim rootFrame = CType(Window.Current.Content, Frame)
            Dim page = CType(rootFrame.Content, MainPage)
    
            ' Call DisplayImages with root folder from camera storage.
            page.DisplayImages(CType(args.Files(0), Windows.Storage.StorageFolder))
        End If
    
        If args.Verb = "copy" Then
            Dim rootFrame = CType(Window.Current.Content, Frame)
            Dim page = CType(rootFrame.Content, MainPage)
    
            ' Call CopyImages with root folder from camera storage.
            page.CopyImages(CType(args.Files(0), Windows.Storage.StorageFolder))
        End If
    
        MyBase.OnFileActivated(args)
    End Sub
    
  2. Save and close the App.xaml.cs file.

4. Add code to display images

  • In the MainPage.xaml.cs or MainPage.xaml.vb file add the following code to the MainPage class.

    async internal void DisplayImages(Windows.Storage.StorageFolder rootFolder)
    {
        // Display images from first folder in root\DCIM.
        var dcimFolder = await rootFolder.GetFolderAsync("DCIM");
        var folderList = await dcimFolder.GetFoldersAsync();
        var cameraFolder = folderList[0];
        var fileList = await cameraFolder.GetFilesAsync();
        for (int i = 0; i < fileList.Count; i++)
        {
            var file = (Windows.Storage.StorageFile)fileList[i];
            WriteMessageText(file.Name + "\n");
            DisplayImage(file, i);
        }
    }
    
    async private void DisplayImage(Windows.Storage.IStorageItem file, int index)
    {
        try
        {
            var sFile = (Windows.Storage.StorageFile)file;
            Windows.Storage.Streams.IRandomAccessStream imageStream =
                await sFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
            Windows.UI.Xaml.Media.Imaging.BitmapImage imageBitmap =
                new Windows.UI.Xaml.Media.Imaging.BitmapImage();
            imageBitmap.SetSource(imageStream);
            var element = new Image();
            element.Source = imageBitmap;
            element.Height = 100;
            Thickness margin = new Thickness();
            margin.Top = index * 100;
            element.Margin = margin;
            FilesCanvas.Children.Add(element);
        }
        catch (Exception e)
        {
           WriteMessageText(e.Message + "\n");
        }
    }
    
    // Write a message to MessageBlock on the UI thread.
    private Windows.UI.Core.CoreDispatcher messageDispatcher = Window.Current.CoreWindow.Dispatcher;
    
    private void WriteMessageText(string message, bool overwrite = false)
    {
        messageDispatcher.InvokeAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
            (s, a) =>
            {
                if (overwrite)
                    FilesBlock.Text = message;
                else
                    FilesBlock.Text += message;
            }, this, null);
    }
    
    Friend Async Sub DisplayImages(rootFolder As Windows.Storage.StorageFolder)
    
        ' Display images from first folder in root\DCIM.
        Dim dcimFolder = Await rootFolder.GetFolderAsync("DCIM")
        Dim folderList = Await dcimFolder.GetFoldersAsync()
        Dim cameraFolder = folderList(0)
    
        Dim fileList = Await cameraFolder.GetFilesAsync()
    
        For i = 0 To fileList.Count - 1
            Dim file = CType(fileList(i), Windows.Storage.StorageFile)
            WriteMessageText(file.Name & vbCr)
            DisplayImage(file, i)
        Next
    End Sub
    
    Private Async Sub DisplayImage(file As Windows.Storage.IStorageItem, index As Integer)
        Try
            Dim sFile = CType(file, Windows.Storage.StorageFile)
            Dim imageStream = Await sFile.OpenAsync(Windows.Storage.FileAccessMode.Read)
            Dim imageBitmap = New Windows.UI.Xaml.Media.Imaging.BitmapImage()
            imageBitmap.SetSource(imageStream)
            Dim element = New Image()
            element.Source = imageBitmap
            element.Height = 100
            Dim Margin = New Thickness()
            Margin.Top = index * 100
            element.Margin = Margin
            FilesCanvas.Children.Add(element)
        Catch e As Exception
    
            WriteMessageText(e.Message & vbCr)
        End Try
    End Sub
    
    
    ' Write a message to MessageBlock on the UI thread.
    
    Private Async Sub WriteMessageText(message As String, Optional overwrite As Boolean = False)
        Await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
            Sub()
                If overwrite Then
                    FilesBlock.Text = message
                Else
                    FilesBlock.Text &= message
                End If
            End Sub)
    End Sub
    

5. Add code to copy images

  • In the MainPage.xaml.cs or MainPage.xaml.vb file add the following code to the MainPage class.

    async internal void CopyImages(Windows.Storage.StorageFolder rootFolder)
    {
        // Copy images from first folder in root\DCIM.
        var dcimFolder = await rootFolder.GetFolderAsync("DCIM");
        var folderList = await dcimFolder.GetFoldersAsync();
        var cameraFolder = folderList[0];
        var fileList = await cameraFolder.GetFilesAsync();
    
        try
        {
            var folderName = "Images " + DateTime.Now.ToString("yyyy-MM-dd HHmmss");
            Windows.Storage.StorageFolder imageFolder = await
                Windows.Storage.KnownFolders.PicturesLibrary.CreateFolderAsync(folderName);
    
            foreach (Windows.Storage.IStorageItem file in fileList)
            {
                CopyImage(file, imageFolder);
            }
        }
        catch (Exception e)
        {
            WriteMessageText("Failed to copy images.\n" + e.Message + "\n");
        }
    }
    
    async internal void CopyImage(Windows.Storage.IStorageItem file,
                                  Windows.Storage.StorageFolder imageFolder)
    {
        try
        {
            Windows.Storage.StorageFile sFile = (Windows.Storage.StorageFile)file;
            await sFile.CopyAsync(imageFolder, sFile.Name);
            WriteMessageText(sFile.Name + " copied.\n");
        }
        catch (Exception e)
        {
            WriteMessageText("Failed to copy file.\n" + e.Message + "\n");
        }
    }
    
    Friend Async Sub CopyImages(rootFolder As Windows.Storage.StorageFolder)
    
        ' Copy images from first folder in root\DCIM.
        Dim dcimFolder = Await rootFolder.GetFolderAsync("DCIM")
        Dim folderList = Await dcimFolder.GetFoldersAsync()
        Dim cameraFolder = folderList(0)
        Dim fileList = Await cameraFolder.GetFilesAsync()
    
        Try
            Dim folderName = "Images " & DateTime.Now.ToString("yyyy-MM-dd HHmmss")
            Dim imageFolder =
                Await Windows.Storage.KnownFolders.PicturesLibrary.CreateFolderAsync(folderName)
    
            For Each file In fileList
                CopyImage(file, imageFolder)
            Next
        Catch e As Exception
            WriteMessageText("Failed to copy images." & vbCr & e.Message & vbCr)
        End Try
    End Sub
    
    Friend Async Sub CopyImage(file As Windows.Storage.IStorageItem,
                               imageFolder As Windows.Storage.StorageFolder)
        Try
            Dim sFile = CType(file, Windows.Storage.StorageFile)
            Await sFile.CopyAsync(imageFolder, sFile.Name)
            WriteMessageText(sFile.Name & " copied." & vbCr)
        Catch e As Exception
            WriteMessageText("Failed to copy file." & vbCr & e.Message & vbCr)
        End Try
    End Sub
    

6. Build and run the application

  1. Press F5 to build and deploy the app (in debug mode).
  2. To run your app, insert a camera memory card or another storage device from a camera into your PC. Then, select one of the content event options that you specified in your package.appxmanifest file from the AutoPlay list of options. This sample code only displays or copies pictures in the DCIM folder of a camera memory card. If your camera memory card stores pictures in an AVCHD or PRIVATE\ACHD folder, you will need to update the code accordingly. Note  If you don't have a camera memory card, you can use a flash drive if it has a folder named DCIM in the root and if the DCIM folder has a subfolder that contains images.  

Summary and next steps

In this tutorial, you created an app that displays image files or copies them to Pictures. You registered the app for the AutoPlay ShowPicturesOnArrival content event.

AutoPlay raises content events for content shared between PCs using proximity (tapping). You can use the steps and code in this quickstart to handle files that are shared between PCs that use proximity. The following table lists the AutoPlay content events that are available for sharing content by using proximity.

Action AutoPlay content event
Sharing music PlayMusicFilesOnArrival
Sharing videos PlayVideoFilesOnArrival

 

When files are shared by using proximity, the Files property of the FileActivatedEventArgs object contains a reference to a root folder that contains all of the shared files.

Auto-launching with AutoPlay

Roadmap for Windows Runtime apps using C# or Visual Basic