借助自动播放功能自动启动Auto-launching with AutoPlay

当用户将设备连接到 PC 时,可以使用 自动播放 功能提供应用作为选项。You can use AutoPlay to provide your app as an option when a user connects a device to their PC. 这包括非卷设备(如相机或媒体播放器)或卷设备(如 U 盘、SD 卡或 DVD)。This includes non-volume devices such as a camera or media player, or volume devices such as a USB thumb drive, SD card, or DVD. 还可以使用自动播放功能在用户使用邻近感应(点击)在两台电脑之间共享文件时,将应用作为一个选项提供。You can also use AutoPlay to offer your app as an option when users share files between two PCs by using proximity (tapping).

注意   如果你是设备制造商,并且想要将Microsoft Store 设备应用程序作为设备的自动播放处理程序,则可以在设备元数据中标识该应用程序。Note  If you are a device manufacturer and you want to associate your Microsoft Store device app as an AutoPlay handler for your device, you can identify that app in the device metadata. 有关详细信息,请参阅 Microsoft Store 设备应用的自动播放For more info, see AutoPlay for Microsoft Store device apps.

注册自动播放内容Register for AutoPlay content

可以将应用注册为自动播放内容事件的选项。You can register apps as options for AutoPlay content events. 当卷设备(如相机内存卡、指状驱动器或 DVD)插入到电脑时,会引发自动播放内容事件。AutoPlay content events are raised when a volume device such as a camera memory card, thumb drive, or DVD is inserted into the PC. 下面我们介绍如何在插入来自相机的卷设备时,将应用标识为的自动播放选项。Here we show how to identify your app as an AutoPlay option when a volume device from a camera is inserted.

在本教程中,你创建了一个用于显示图像文件或将其复制到“图片”的应用。In this tutorial, you created an app that displays image files or copies them to Pictures. 为自动播放 ShowPicturesOnArrival 内容事件注册了应用。You registered the app for the AutoPlay ShowPicturesOnArrival content event.

“自动播放”功能还为在使用邻近感应(点击)的电脑之间共享的内容引发内容事件。AutoPlay also raises content events for content shared between PCs using proximity (tapping). 你可以使用本部分中的步骤和代码来处理使用邻近感应的电脑之间共享的文件。You can use the steps and code in this section 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 PlayMusicFilesOnArrivalPlayMusicFilesOnArrival
共享视频Sharing videos PlayVideoFilesOnArrivalPlayVideoFilesOnArrival

  使用邻近感应共享文件时,FileActivatedEventArgs 对象的 Files 属性包含对拥有所有共享文件的根文件夹的引用。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.

步骤 1:创建新项目并添加自动播放声明Step 1: Create a new project and add AutoPlay declarations

  1. 打开 Microsoft Visual Studio,然后从文件菜单中选择新建项目Open Microsoft Visual Studio and select New Project from the File menu. Visual C# 部分的Windows下,选择空白应用(通用 Windows)In the Visual C# section, under Windows, select Blank App (Universal Windows). 将应用命名为 AutoPlayDisplayOrCopyImages 并单击确定Name the app AutoPlayDisplayOrCopyImages and click OK.
  2. 打开 Package.appxmanifest 文件,选择功能选项卡。选择可移动存储图片库功能。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. 该事件基于卷设备(如 DVD 或 U 盘)的内容。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. 如果卷的根包含 DCIM、AVCHD 或 PRIVATE \ ACHD 文件夹,或如果用户已启用 "自动播放" 控制面板中的 每种类型的媒体的操作 ,并且在卷的根目录中找到了图片,则自动播放将引发 ShowPicturesOnArrival 事件。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. 启动操作部分中,为第一个启动操作输入表 1 中的以下值。In the Launch Actions section, enter the values from Table 1 below for the first launch action.
  5. 自动播放内容项的启动操作部分中,单击新增可添加第二个启动操作。In the Launch Actions section for the AutoPlay Content item, click Add New to add a second launch action. 为第二个启动操作输入表 2 中的以下值。Enter the values in Table 2 below for the second launch action.
  6. 可用声明下拉列表中,选择文件类型关联,然后单击添加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. 文件类型字段设置为 .jpgSet the File Type field to .jpg. 支持的文件类型部分中,将新文件关联的文件类型字段设置为 .pngIn 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.
  7. 保存并关闭清单文件。Save and close the manifest file.

表 1Table 1

设置Setting Value
谓词Verb showshow
操作显示名称Action Display Name 显示图片Show Pictures
内容事件Content Event ShowPicturesOnArrivalShowPicturesOnArrival

操作显示名称设置标识自动播放为你的应用显示的字符串。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. 您可以通过检查传递到应用程序的启动事件参数的 verb 属性来确定用户选择的选项。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.

表 2Table 2

设置Setting Value
谓词Verb copycopy
操作显示名称Action Display Name 将图片复制到库Copy Pictures Into Library
内容事件Content Event ShowPicturesOnArrivalShowPicturesOnArrival

步骤 2:添加 XAML UIStep 2: Add XAML UI

打开 MainPage.xaml 文件并将以下 XAML 添加到默认的 <Grid> 部分。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:添加初始化代码Step 3: Add initialization code

此步骤中的代码检查 Verb 属性中的 verb 值,该属性是在 OnFileActivated 事件期间传递给应用的启动参数之一。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. 可以从 Files 属性的第一个元素检索该文件夹。You can retrieve this folder from the first element of the Files property.

打开 App.xaml.cs 文件,然后将以下代码添加到 App 类。Open the App.xaml.cs 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);
}

注意   DisplayImages CopyImages 在以下步骤中添加了和方法。Note  The DisplayImages and CopyImages methods are added in the following steps.

步骤 4:添加用于显示图像的代码Step 4: Add code to display images

在 MainPage.xaml.cs 文件中,将以下代码添加到 MainPage 类。In the MainPage.xaml.cs 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 async void WriteMessageText(string message, bool overwrite = false)
{
    await messageDispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
        () =>
        {
            if (overwrite)
                FilesBlock.Text = message;
            else
                FilesBlock.Text += message;
        });
}

步骤 5:添加用于复制图像的代码Step 5: Add code to copy images

在 MainPage.xaml.cs 文件中,将以下代码添加到 MainPage 类。In the MainPage.xaml.cs 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");
    }
}

步骤 6:生成并运行应用Step 6: Build and run the app

  1. 按 F5 生成并部署应用(在调试模式下)。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. 然后,从自动播放选项列表中选择在你的 package.appxmanifest 文件中指定的内容事件选项之一。Then, select one of the content event options that you specified in your package.appxmanifest file from the AutoPlay list of options. 此示例代码仅显示或复制相机内存卡的 DCIM 文件夹中的图片。This sample code only displays or copies pictures in the DCIM folder of a camera memory card. 如果照相机内存卡将图片存储在 AVCHD 或 PRIVATE \ ACHD 文件夹中,则需要相应地更新代码。If your camera memory card stores pictures in an AVCHD or PRIVATE\ACHD folder, you will need to update the code accordingly. 注意   如果没有照相机内存卡,则可以使用闪存驱动器(如果根中有一个名为DCIM的文件夹),并且 DCIM 文件夹具有包含图像的子文件夹。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.

注册自动播放设备Register for an AutoPlay device

可以将应用注册为自动播放设备事件的选项。You can register apps as options for AutoPlay device events. 自动播放设备事件会在设备连接到电脑时引发。AutoPlay device events are raised when a device is connected to a PC.

下面显示了如何将应用标识为在将相机连接到电脑时的自动播放选项。Here we show how to identify your app as an AutoPlay option when a camera is connected to a PC. 应用注册为 WPD \ ImageSourceAutoPlay 事件的处理程序。The app registers as a handler for the WPD\ImageSourceAutoPlay event. 当相机和其他图像设备通知事件它们为使用 MTP 的 ImageSource 时,此为 Windows Portable Device (WPD) 系统引发的常见事件。This is a common event that the Windows Portable Device (WPD) system raises when cameras and other imaging devices notify it that they are an ImageSource using MTP. 有关详细信息,请参阅 Windows Portable DeviceFor more info, see Windows Portable Devices.

重要提示   StorageDevice api 是桌面设备系列的一部分。Important  The Windows.Devices.Portable.StorageDevice APIs are part of the desktop device family. 应用只能在属于桌面设备系列的 Windows 10 设备(例如电脑)上使用这些 API。Apps can use these APIs only on Windows 10 devices in the desktop device family, such as PCs.

 

步骤 1:创建新项目并添加自动播放声明Step 1: Create a new project and add AutoPlay declarations

  1. 打开 Visual Studio,然后从文件菜单中选择新建项目Open Visual Studio and select New Project from the File menu. Visual C# 部分的Windows下,选择空白应用(通用 Windows)In the Visual C# section, under Windows, select Blank App (Universal Windows). 将应用命名为 AutoPlayDevice _ 相机 ,然后单击 "确定"。Name the app AutoPlayDevice_Camera and click OK.
  2. 打开 Package.appxmanifest 文件,选择功能选项卡。选择可移动存储功能。Open the Package.appxmanifest file and select the Capabilities tab. Select the Removable Storage capability. 这会使该应用能够访问作为可移动存储卷设备的相机上的数据。This gives the app access to the data on the camera as a removable storage volume device.
  3. 在清单文件中,选择声明选项卡。在可用声明下拉列表中,选择自动播放设备,然后单击添加In the manifest file, select the Declarations tab. In the Available Declarations drop-down list, select AutoPlay Device and click Add. 选择已添加到支持的声明列表中的新自动播放设备项。Select the new AutoPlay Device item that was added to the Supported Declarations list.
  4. 自动播放设备声明会在“自动播放”引发已知事件的设备事件时将你的应用标识为一个选项。An AutoPlay Device declaration identifies your app as an option when AutoPlay raises a device event for known events. 启动操作部分中,为第一个启动操作输入下表中的以下值。In the Launch Actions section, enter the values in the table below for the first launch action.
  5. 可用声明下拉列表中,选择文件类型关联,然后单击添加In the Available Declarations drop-down list, select File Type Associations and click Add. 在新的 文件类型关联 声明的属性中,将 " 显示名称 " 字段设置为 " 显示照相机中的图像 ",将 " 名称 " 字段设置为 " 照相机 _ association1"。In the Properties of the new File Type Associations declaration, set the Display Name field to Show Images from Camera and the Name field to camera_association1. 支持的文件类型部分中,单击新增(如果需要)。In the Supported File Types section, click Add New (if needed). 文件类型字段设置为 .jpgSet the File Type field to .jpg. 支持的文件类型部分中,再次单击新增In the Supported File Types section, click Add New again. 将新文件关联的文件类型字段设置为 .pngSet 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.
  6. 保存并关闭清单文件。Save and close the manifest file.
设置Setting Value
谓词Verb showshow
操作显示名称Action Display Name 显示图片Show Pictures
内容事件Content Event WPD \ ImageSourceWPD\ImageSource

操作显示名称设置标识自动播放为你的应用显示的字符串。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. 您可以通过检查传递到应用程序的启动事件参数的 verb 属性来确定用户选择的选项。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. 有关在单个应用中使用多个谓词的示例,请参阅注册自动播放内容For an example of using multiple verbs in a single app, see Register for AutoPlay content.

步骤 2:添加桌面扩展的程序集引用Step 2: Add assembly reference for the desktop extensions

访问 Windows 便携设备上的存储所需的 API Windows.Devices.Portable.StorageDevice桌面设备系列的一部分。The APIs required to access storage on a Windows Portable Device, Windows.Devices.Portable.StorageDevice, are part of the desktop desktop device family. 这表示使用这些 API 需要特殊的程序集,并且这些调用仅适用于桌面设备系列中的设备(例如电脑)。This means a special assembly is required to use the APIs and those calls will only work on a device in the desktop device family (such as a PC).

  1. 解决方案资源管理器中,右键单击引用,然后单击添加引用...In Solution Explorer, right click on References and then Add Reference....
  2. 展开通用 Windows 并单击扩展Expand Universal Windows and click Extensions.
  3. 然后选择适用于 UWP 的 Windows 桌面扩展并单击确定Then select Windows Desktop Extensions for the UWP and click OK.

步骤 3:添加 XAML UIStep 3: Add XAML UI

打开 MainPage.xaml 文件并将以下 XAML 添加到默认的 <Grid> 部分。Open the MainPage.xaml file and add the following XAML to the default <Grid> section.

<StackPanel Orientation="Vertical" Margin="10,0,-10,0">
    <TextBlock FontSize="24">Device Information</TextBlock>
    <StackPanel Orientation="Horizontal">
        <TextBlock x:Name="DeviceInfoTextBlock" FontSize="18" Height="400" Width="400" VerticalAlignment="Top" />
        <ListView x:Name="ImagesList" HorizontalAlignment="Left" Height="400" VerticalAlignment="Top" Width="400">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Vertical">
                        <Image Source="{Binding Path=Source}" />
                        <TextBlock Text="{Binding Path=Name}" />
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
            <ListView.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapGrid Orientation="Horizontal" ItemHeight="100" ItemWidth="120"></WrapGrid>
                </ItemsPanelTemplate>
            </ListView.ItemsPanel>
        </ListView>
    </StackPanel>
</StackPanel>

步骤 4:添加激活代码Step 4: Add activation code

此步骤中的代码通过将相机的设备信息 ID 传递给 FromId 方法来以 StorageDevice 形式引用相机。The code in this step references the camera as a StorageDevice by passing the device information Id of the camera to the FromId method. 通过以下方法获取相机的设备信息 ID:首先将事件参数强制转换为 DeviceActivatedEventArgs,然后从 DeviceInformationId 属性获取值。The device information Id of the camera is obtained by first casting the event arguments as DeviceActivatedEventArgs, and then getting the value from the DeviceInformationId property.

打开 App.xaml.cs 文件,然后将以下代码添加到 App 类。Open the App.xaml.cs file and add the following code to the App class.

protected override void OnActivated(IActivatedEventArgs args)
{
   if (args.Kind == ActivationKind.Device)
   {
      Frame rootFrame = null;
      // Ensure that the current page exists and is activated
      if (Window.Current.Content == null)
      {
         rootFrame = new Frame();
         rootFrame.Navigate(typeof(MainPage));
         Window.Current.Content = rootFrame;
      }
      else
      {
         rootFrame = Window.Current.Content as Frame;
      }
      Window.Current.Activate();

      // Make sure the necessary APIs are present on the device
      bool storageDeviceAPIPresent =
      Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Devices.Portable.StorageDevice");

      if (storageDeviceAPIPresent)
      {
         // Reference the current page as type MainPage
         var mPage = rootFrame.Content as MainPage;

         // Cast the activated event args as DeviceActivatedEventArgs and show images
         var deviceArgs = args as DeviceActivatedEventArgs;
         if (deviceArgs != null)
         {
            mPage.ShowImages(Windows.Devices.Portable.StorageDevice.FromId(deviceArgs.DeviceInformationId));
         }
      }
      else
      {
         // Handle case where APIs are not present (when the device is not part of the desktop device family)
      }

   }

   base.OnActivated(args);
}

注意   此 ShowImages 方法在以下步骤中添加。Note  The ShowImages method is added in the following step.

步骤 5:添加用于显示设备信息的代码Step 5: Add code to display device information

可以从 StorageDevice 类的属性中获取有关相机的信息。You can obtain information about the camera from the properties of the StorageDevice class. 此步骤中的代码在应用运行时,向用户显示设备名称和其他信息。The code in this step displays the device name and other info to the user when the app runs. 此代码随后调用 GetImageList 和 GetThumbnail 方法,这些方法将在下一步中添加,用于显示相机上所存储图像的缩略图。The code then calls the GetImageList and GetThumbnail methods, which you will add in the next step, to display thumbnails of the images stored on the camera

在 MainPage.xaml.cs 文件中,将以下代码添加到 MainPage 类。In the MainPage.xaml.cs file, add the following code to the MainPage class.

private Windows.Storage.StorageFolder rootFolder;

internal async void ShowImages(Windows.Storage.StorageFolder folder)
{
    DeviceInfoTextBlock.Text = "Display Name = " + folder.DisplayName + "\n";
    DeviceInfoTextBlock.Text += "Display Type =  " + folder.DisplayType + "\n";
    DeviceInfoTextBlock.Text += "FolderRelativeId = " + folder.FolderRelativeId + "\n";

    // Reference first folder of the device as the root
    rootFolder = (await folder.GetFoldersAsync())[0];
    var imageList = await GetImageList(rootFolder);

    foreach (Windows.Storage.StorageFile img in imageList)
    {
        ImagesList.Items.Add(await GetThumbnail(img));
    }
}

注意   GetImageList GetThumbnail 以下步骤添加了和方法。Note  The GetImageList and GetThumbnail methods are added in the following step.

步骤 6:添加用于显示图像的代码Step 6: Add code to display images

此步骤中的代码显示相机上所存储图像的缩略图。The code in this step displays thumbnails of the images stored on the camera. 此代码对相机进行异步调用以获取缩略图。The code makes asynchronous calls to the camera to get the thumbnail image. 但是,只有在上一个异步调用完成后,才会进行下一个异步调用。However, the next asynchronous call doesn't occur until the previous asynchronous call completes. 这可确保一次仅对相机发出一个请求。This ensures that only one request is made to the camera at a time.

在 MainPage.xaml.cs 文件中,将以下代码添加到 MainPage 类。In the MainPage.xaml.cs file, add the following code to the MainPage class.

async private System.Threading.Tasks.Task<List<Windows.Storage.StorageFile>> GetImageList(Windows.Storage.StorageFolder folder)
{
    var result = await folder.GetFilesAsync();
    var subFolders = await folder.GetFoldersAsync();
    foreach (Windows.Storage.StorageFolder f in subFolders)
        result = result.Union(await GetImageList(f)).ToList();

    return (from f in result orderby f.Name select f).ToList();
}

async private System.Threading.Tasks.Task<Image> GetThumbnail(Windows.Storage.StorageFile img)
{
    // Get the thumbnail to display
    var thumbnail = await img.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.SingleItem,
                                                100,
                                                Windows.Storage.FileProperties.ThumbnailOptions.UseCurrentScale);

    // Create a XAML Image object bind to on the display page
    var result = new Image();
    result.Height = thumbnail.OriginalHeight;
    result.Width = thumbnail.OriginalWidth;
    result.Name = img.Name;
    var imageBitmap = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
    imageBitmap.SetSource(thumbnail);
    result.Source = imageBitmap;

    return result;
}

步骤 7:生成并运行应用Step 7: Build and run the app

  1. 按 F5 生成并部署应用(在调试模式下)。Press F5 to build and deploy the app (in debug mode).
  2. 若要运行你的应用,请将相机连接到你的计算机。To run your app, connect a camera to your machine. 然后从“自动播放”选项列表中选择该应用。Then select the app from the AutoPlay list of options. 注意   并非所有照相机都公布WPD \ ImageSource自动播放设备事件。Note  Not all cameras advertise for the WPD\ImageSource AutoPlay device event.

配置可移动存储Configure removable storage

当卷设备(如内存卡或指状驱动器)连接到电脑时,你可以将这些设备标识为自动播放设备。You can identify a volume device such as a memory card or thumb drive as an AutoPlay device when the volume device is connected to a PC. 当你希望关联特定的应用以便为卷设备的用户提供自动播放功能时,这尤其有用。This is especially useful when you want to associate a specific app for AutoPlay to present to the user for your volume device.

下面显示了如何将卷设备标识为自动播放设备。Here we show how to identify your volume device as an AutoPlay device.

若要将卷设备标识为自动播放设备,请在设备的根驱动器中添加一个 autorun.inf 文件。To identify your volume device as an AutoPlay device, add an autorun.inf file to the root drive of your device. 在 autorun.inf 文件中,向 AutoRun 部分中添加一个 CustomEvent 键。In the autorun.inf file, add a CustomEvent key to the AutoRun section. 当卷设备连接到电脑时,自动播放将查找 autorun.inf 文件并将你的卷视为一台设备。When your volume device connects to a PC, AutoPlay will find the autorun.inf file and treat your volume as a device. 自动播放将通过使用你为 CustomEvent 键提供的名称创建一个自动播放事件。AutoPlay will create an AutoPlay event by using the name that you supplied for the CustomEvent key. 然后,你可以创建一个应用并将其注册为该自动播放事件的处理程序。You can then create an app and register the app as a handler for that AutoPlay event. 当设备连接到电脑时,自动播放功能会将该应用显示为卷设备的处理程序。When the device is connected to the PC, AutoPlay will show your app as a handler for your volume device. 有关 autorun.inf 文件的详细信息,请参阅 autorun.inf 条目For more info on autorun.inf files, see autorun.inf entries.

步骤 1:创建 autorun.inf 文件Step 1: Create an autorun.inf file

在卷设备的根驱动器中,添加一个名为 autorun.inf 的文件。In the root drive of your volume device, add a file named autorun.inf. 打开 autorun.inf 文件并添加以下文本。Open the autorun.inf file and add the following text.

[AutoRun]
CustomEvent=AutoPlayCustomEventQuickstart

步骤 2:创建新项目并添加自动播放声明Step 2: Create a new project and add AutoPlay declarations

  1. 打开 Visual Studio,然后从文件菜单中选择新建项目Open Visual Studio and select New Project from the File menu. Visual C# 部分的Windows下,选择空白应用(通用 Windows)In the Visual C# section, under Windows, select Blank App (Universal Windows). 将该应用程序命名为 AutoPlayCustomEvent,然后单击确定Name the application AutoPlayCustomEvent and click OK.

  2. 打开 Package.appxmanifest 文件,选择功能选项卡。选择可移动存储功能。Open the Package.appxmanifest file and select the Capabilities tab. Select the Removable Storage capability. 这使应用能够访问可移动存储设备上的文件和文件夹。This gives the app access to the files and folders on removable storage devices.

  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.

    注意   此外,还可以选择为自定义自动播放事件添加自动播放设备声明。Note  Alternatively, you can also choose to add an AutoPlay Device declaration for your custom AutoPlay event.  

  4. 自动播放内容事件声明的启动操作部分中,为第一个启动操作输入下表中的以下值。In the Launch Actions section for your AutoPlay Content event declaration, enter the values in the table below for the first launch action.

  5. 可用声明下拉列表中,选择文件类型关联,然后单击添加In the Available Declarations drop-down list, select File Type Associations and click Add. 在新的文件类型关联声明的属性中,将 "显示名称" 字段设置为 "ms 文件",将 "名称" 字段显示ms _ 关联In the Properties of the new File Type Associations declaration, set the Display Name field to Show .ms Files and the Name field to ms_association. 支持的文件类型部分中,单击新增In the Supported File Types section, click Add New. 文件类型字段设置为 .msSet the File Type field to .ms. 对于内容事件,“自动播放”功能会筛选掉任何未与应用显式关联的文件类型。For content events, AutoPlay filters out any file types that aren't explicitly associated with your app.

  6. 保存并关闭清单文件。Save and close the manifest file.

设置Setting Value
谓词Verb showshow
操作显示名称Action Display Name 显示文件Show Files
内容事件Content Event AutoPlayCustomEventQuickstartAutoPlayCustomEventQuickstart

内容事件值是在 autorun.inf 文件中为 CustomEvent 键提供的文本。The Content Event value is the text that you supplied for the CustomEvent key in your autorun.inf file. 操作显示名称设置标识自动播放为你的应用显示的字符串。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. 您可以通过检查传递到应用程序的启动事件参数的 verb 属性来确定用户选择的选项。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.

步骤 3:添加 XAML UIStep 3: Add XAML UI

打开 MainPage.xaml 文件并将以下 XAML 添加到默认的 <Grid> 部分。Open the MainPage.xaml file and add the following XAML to the default <Grid> section.

<StackPanel Orientation="Vertical">
    <TextBlock FontSize="28" Margin="10,0,800,0">Files</TextBlock>
    <TextBlock x:Name="FilesBlock" FontSize="22" Height="600" Margin="10,0,800,0" />
</StackPanel>

步骤 4:添加激活代码Step 4: Add activation code

此步骤中的代码调用一个方法以显示卷设备的根驱动器中的文件夹。The code in this step calls a method to display the folders in the root drive of your volume device. 对于“自动播放内容”事件,“自动播放”功能在执行 OnFileActivated 事件期间传递给应用程序的启动参数中传递存储设备的根文件夹。For the AutoPlay content events, AutoPlay passes the root folder of the storage device in the startup arguments passed to the application during the OnFileActivated event. 可以从 Files 属性的第一个元素检索该文件夹。You can retrieve this folder from the first element of the Files property.

打开 App.xaml.cs 文件,然后将以下代码添加到 App 类。Open the App.xaml.cs file and add the following code to the App class.

protected override void OnFileActivated(FileActivatedEventArgs args)
{
    var rootFrame = Window.Current.Content as Frame;
    var page = rootFrame.Content as MainPage;

    // Call ShowFolders with root folder from device storage.
    page.DisplayFiles(args.Files[0] as Windows.Storage.StorageFolder);

    base.OnFileActivated(args);
}

注意   此 DisplayFiles 方法在以下步骤中添加。Note  The DisplayFiles method is added in the following step.

 

步骤 5:添加用于显示文件夹的代码Step 5: Add code to display folders

在 MainPage.xaml.cs 文件中,将以下代码添加到 MainPage 类。In the MainPage.xaml.cs file add the following code to the MainPage class.

internal async void DisplayFiles(Windows.Storage.StorageFolder folder)
{
    foreach (Windows.Storage.StorageFile f in await ReadFiles(folder, ".ms"))
    {
        FilesBlock.Text += "  " + f.Name + "\n";
    }
}

internal async System.Threading.Tasks.Task<IReadOnlyList<Windows.Storage.StorageFile>>
    ReadFiles(Windows.Storage.StorageFolder folder, string fileExtension)
{
    var options = new Windows.Storage.Search.QueryOptions();
    options.FileTypeFilter.Add(fileExtension);
    var query = folder.CreateFileQueryWithOptions(options);
    var files = await query.GetFilesAsync();

    return files;
}

步骤 6:生成并运行应用Step 6: Build and run the qpp

  1. 按 F5 生成并部署应用(在调试模式下)。Press F5 to build and deploy the app (in debug mode).
  2. 若要运行应用,请将内存卡或其他存储设备插入电脑。To run your app, insert a memory card or another storage device into your PC. 然后从“自动播放”处理程序选项的列表中选择你的应用。Then select your app from the list of AutoPlay handler options.

自动播放事件参考AutoPlay event reference

使用自动播放系统,应用可以注册各种设备和卷(磁盘)到达事件。The AutoPlay system allows apps to register for a variety of device and volume (disk) arrival events. 若要注册自动播放内容事件,则必须在程序包清单中启用可移动存储功能。To register for AutoPlay content events, you must enable the Removable Storage capability in your package manifest. 此表显示了可以注册的事件及其引发时间。This table shows the events that you can register for and when they are raised.

方案Scenario 事件Event 描述Description
使用相机上的照片Using photos on a Camera WPD\ImageSourceWPD\ImageSource 针对标识为 Windows Portable Devices 且提供 ImageSource 功能的相机引发。Raised for cameras that are identified as Windows Portable Devices and offer the ImageSource capability.
使用自动播放器上的音乐Using music on an audio player WPD\AudioSourceWPD\AudioSource 针对标识为 Windows Portable Devices 且提供 AudioSource 功能的媒体播放器引发。Raised for media players that are identified as Windows Portable Devices and offer the AudioSource capability.
使用摄像机上的视频Using videos on a video camera WPD\VideoSourceWPD\VideoSource 针对标识为 Windows Portable Devices 且提供 VideoSource 功能的摄像机引发。Raised for video cameras that are identified as Windows Portable Devices and offer the VideoSource capability.
访问所连接的闪存驱动器或外部硬盘驱动器Access a connected flash drive or external hard drive StorageOnArrivalStorageOnArrival 在驱动器或卷连接到电脑时引发。Raised when a drive or volume is connected to the PC. 如果驱动器或卷的磁盘根目录中包含 DCIM、AVCHD 或 PRIVATE\ACHD 文件夹,则会改为引发 ShowPicturesOnArrival 事件。If the drive or volume contains a DCIM, AVCHD, or PRIVATE\ACHD folder in the root of the disk, the ShowPicturesOnArrival event is raised instead.
使用大容量存储(旧功能)中的照片Using photos from mass storage (legacy) ShowPicturesOnArrivalShowPicturesOnArrival 当驱动器或卷的磁盘根目录中包含 DCIM、AVCHD 或 PRIVATE\ACHD 文件夹时引发。Raised when a drive or volume contains a DCIM, AVCHD, or PRIVATE\ACHD folder in the root of the disk. 如果用户已启用自动播放控制面板中的为每种媒体类型选择相应的操作,则自动播放会检查连接到电脑的卷以确定磁盘中内容的类型。IIf a user has enabled Choose what to do with each type of media in the AutoPlay Control Panel, AutoPlay will examine a volume connected to the PC to determine the type of content on the disk. 找到图片时,将引发 ShowPicturesOnArrivalWhen pictures are found, ShowPicturesOnArrival is raised.
使用邻近感应共享(点击并发送)接收照片Receiving photos with Proximity Sharing (tap and send) ShowPicturesOnArrivalShowPicturesOnArrival 当用户使用邻近感应(点击并发送)发送内容时,自动播放会检查共享文件以确定内容的类型。When users send content with using proximity (tap and send), AutoPlay will examine the shared files to determine the type of content. 如果找到图片,则会引发 ShowPicturesOnArrivalIf pictures are found, ShowPicturesOnArrival is raised.
使用大容量存储(旧功能)中的音乐Using music from mass storage (legacy) PlayMusicFilesOnArrivalPlayMusicFilesOnArrival 如果用户已启用 "自动播放" 控制面板中 每种类型媒体的操作 ,则自动播放将检查连接到电脑的卷以确定磁盘上的内容类型。If a user has enabled Choose what to do with each type of media in the AutoPlay Control Panel, AutoPlay will examine a volume connected to the PC to determine the type of content on the disk. 找到音乐文件时,将引发 PlayMusicFilesOnArrivalWhen music files are found, PlayMusicFilesOnArrival is raised.
使用邻近感应共享(点击并发送)接收音乐Receiving music with Proximity Sharing (tap and send) PlayMusicFilesOnArrivalPlayMusicFilesOnArrival 当用户使用邻近感应(点击并发送)发送内容时,自动播放会检查共享文件以确定内容的类型。When users send content with using proximity (tap and send), AutoPlay will examine the shared files to determine the type of content. 如果找到音乐文件,则会引发 PlayMusicFilesOnArrivalIf music files are found, PlayMusicFilesOnArrival is raised.
使用大容量存储(旧功能)中的视频Using videos from mass storage (legacy) PlayVideoFilesOnArrivalPlayVideoFilesOnArrival 如果用户已启用 "自动播放" 控制面板中 每种类型媒体的操作 ,则自动播放将检查连接到电脑的卷以确定磁盘上的内容类型。If a user has enabled Choose what to do with each type of media in the AutoPlay Control Panel, AutoPlay will examine a volume connected to the PC to determine the type of content on the disk. 找到视频文件时,将引发 PlayVideoFilesOnArrivalWhen video files are found, PlayVideoFilesOnArrival is raised.
使用邻近感应共享(点击并发送)接收视频Receiving videos with Proximity Sharing (tap and send) PlayVideoFilesOnArrivalPlayVideoFilesOnArrival 当用户使用邻近感应(点击并发送)发送内容时,自动播放会检查共享文件以确定内容的类型。When users send content with using proximity (tap and send), AutoPlay will examine the shared files to determine the type of content. 如果找到视频文件,则会引发 PlayVideoFilesOnArrivalIf video files are found, PlayVideoFilesOnArrival is raised.
处理所连接设备中的混合文件集Handling mixed sets of files from a connected device MixedContentOnArrivalMixedContentOnArrival 如果用户已启用 "自动播放" 控制面板中 每种类型媒体的操作 ,则自动播放将检查连接到电脑的卷以确定磁盘上的内容类型。If a user has enabled Choose what to do with each type of media in the AutoPlay Control Panel, AutoPlay will examine a volume connected to the PC to determine the type of content on the disk. 如果未找到特定的内容类型(例如,图片),则会引发 MixedContentOnArrivalIf no specific content type is found (for example, pictures), MixedContentOnArrival is raised.
使用邻近感应共享(点击并发送)处理混合文件集Handling mixed sets of files with Proximity Sharing (tap and send) MixedContentOnArrivalMixedContentOnArrival 当用户使用邻近感应(点击并发送)发送内容时,自动播放会检查共享文件以确定内容的类型。When users send content with using proximity (tap and send), AutoPlay will examine the shared files to determine the type of content. 如果未找到特定的内容类型(例如,图片),则会引发 MixedContentOnArrivalIf no specific content type is found (for example, pictures), MixedContentOnArrival is raised.
处理光学媒体上的视频Handle video from optical media PlayDVDMovieOnArrivalPlayDVDMovieOnArrival
PlayBluRayOnArrivalPlayBluRayOnArrival
PlayVideoCDMovieOnArrivalPlayVideoCDMovieOnArrival
PlaySuperVideoCDMovieOnArrivalPlaySuperVideoCDMovieOnArrival
将光盘插入光驱时,自动播放将检查文件以确定内容的类型。When a disk is inserted into the optical drive, AutoPlay will examine the files to determine the type of content. 发现视频文件时,会引发与光盘类型相对应的事件。When video files are found, the event corresponding to the type of optical disk is raised.
处理光学媒体上的音乐Handle music from optical media PlayCDAudioOnArrivalPlayCDAudioOnArrival
PlayDVDAudioOnArrivalPlayDVDAudioOnArrival
将光盘插入光驱时,自动播放将检查文件以确定内容的类型。When a disk is inserted into the optical drive, AutoPlay will examine the files to determine the type of content. 发现音乐文件时,会引发与光盘类型相对应的事件。When music files are found, the event corresponding to the type of optical disk is raised.
播放增强磁盘Play enhanced disks PlayEnhancedCDOnArrivalPlayEnhancedCDOnArrival
PlayEnhancedDVDOnArrivalPlayEnhancedDVDOnArrival
将光盘插入光驱时,自动播放将检查文件以确定内容的类型。When a disk is inserted into the optical drive, AutoPlay will examine the files to determine the type of content. 发现增强磁盘时,会引发与光盘类型相对应的事件。When an enhanced disk is found, the event corresponding to the type of optical disk is raised.
处理可写入的光盘Handle writeable optical disks HandleCDBurningOnArrivalHandleCDBurningOnArrival
HandleDVDBurningOnArrivalHandleDVDBurningOnArrival
HandleBDBurningOnArrivalHandleBDBurningOnArrival
将光盘插入光驱时,自动播放将检查文件以确定内容的类型。When a disk is inserted into the optical drive, AutoPlay will examine the files to determine the type of content. 发现可写磁盘时,会引发与光盘类型相对应的事件。When a writable disk is found, the event corresponding to the type of optical disk is raised.
处理任何其他设备或卷连接Handle any other device or volume connection UnknownContentOnArrivalUnknownContentOnArrival 在找到与任何“自动播放内容”事件都不匹配的内容时,会针对所有事件引发。Raised for all events in case content is found that does not match any of the AutoPlay content events. 不建议使用此事件。Use of this event is not recommended. 只应当针对你的应用可以处理的特定“自动播放”事件注册你的应用程序。You should only register your application for the specific AutoPlay events that it can handle.

你可以指定“自动播放”使用 autorun.inf 文件中的 CustomEvent 条目来为卷引发自定义的“自动播放内容”事件。You can specify that AutoPlay raise a custom AutoPlay Content event using the CustomEvent entry in the autorun.inf file for a volume. 有关详细信息,请参阅 Autorun.inf 条目For more info, see Autorun.inf entries.

你可以通过向应用的 package.appxmanifest 文件添加扩展,将应用注册为“自动播放内容”或“自动播放设备”事件处理程序。You can register your app as an AutoPlay Content or AutoPlay Device event handler by adding an extension to the package.appxmanifest file for your app. 如果使用 Visual Studio,则可以在声明选项卡中添加自动播放内容自动播放设备。如果要直接编辑应用的 package.appxmanifest 文件,请向将 windows.autoPlayContentwindows.autoPlayDevice 指定为类别的程序包清单添加 Extension 元素。If you are using Visual Studio, you can add an AutoPlay Content or AutoPlay Device declaration in the Declarations tab. If you are editing the package.appxmanifest file for your app directly, add an Extension element to your package manifest that specifies either windows.autoPlayContent or windows.autoPlayDevice as the Category. 例如,程序包清单中的以下条目添加自动播放内容扩展,以将应用注册为 ShowPicturesOnArrival 事件的处理程序。For example, the following entry in the package manifest adds an AutoPlay Content extension to register the app as a handler for the ShowPicturesOnArrival event.

  <Applications>
    <Application Id="AutoPlayHandlerSample.App">
      <Extensions>
        <Extension Category="windows.autoPlayContent">
          <AutoPlayContent>
            <LaunchAction Verb="show" ActionDisplayName="Show Pictures"
                          ContentEvent="ShowPicturesOnArrival" />
          </AutoPlayContent>
        </Extension>
      </Extensions>
    </Application>
  </Applications>