啟動檔案的預設應用程式

重要 API

了解如何啟動檔案的預設應用程式。 許多應用程式都需要使用無法自行處理的檔案。 例如,電子郵件應用程式會接收各種檔案類型,並且需要一種方法在其預設處理程序中啟動這些檔案。 這些步驟示範如何使用 Windows.System.Launcher API 來啟動應用程式無法自行處理之檔案的預設處理程式。

取得檔案物件

首先,取得檔案的 Windows.Storage.StorageFile 物件。

如果該檔案包含在應用程式套件中,則可以使用 Package.InstalledLocation 屬性取得 Windows.Storage.StorageFolder 物件,並使用 Windows.Storage.StorageFolder.GetFileAsync 方法取得 StorageFile 物件。

如果檔案位於已知資料夾中,則可以使用 Windows.Storage.KnownFolders 類別的屬性來取得 StorageFolder,並使用 GetFileAsync 方法來取得 StorageFile 物件。

啟動檔案

Windows 提供數種不同的選項來啟動檔案的預設處理程式。 這些選項會在此圖表和後續各節中說明。

選項 方法 描述
預設啟動 LaunchFileAsync(IStorageFile) 使用預設處理程式啟動指定的檔案。
打開並啟動 LaunchFileAsync(IStorageFile, LauncherOptions) 啟動指定的檔案,讓使用者透過開啟方式對話框挑選處理程式。
使用建議的應用程式後援啟動 LaunchFileAsync(IStorageFile, LauncherOptions) 使用預設處理程式啟動指定的檔案。 如果未在系統上安裝任何處理程式,建議在市集中的應用程式給使用者。
使用所需的剩餘檢視啟動 LaunchFileAsync(IStorageFile, LauncherOptions) (僅限 Windows-only) 使用預設處理程式啟動指定的檔案。 指定啟動後保留在螢幕上的首選項並請求特定的視窗大小。 LauncherOptions.DesiredRemainingView 行動裝置系列不支援。

預設啟動

呼叫 Windows.System.Launcher.LaunchFileAsync(IStorageFile) 方法啟動預設應用程式。 此範例使用 Windows.Storage.StorageFolder.GetFileAsync 方法啟動應用程式套件中包含的映像檔 test.png。

async void DefaultLaunch()
{
   // Path to the file in the app package to launch
   string imageFile = @"images\test.png";
   
   var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile);
   
   if (file != null)
   {
      // Launch the retrieved file
      var success = await Windows.System.Launcher.LaunchFileAsync(file);

      if (success)
      {
         // File launched
      }
      else
      {
         // File launch failed
      }
   }
   else
   {
      // Could not find file
   }
}
async Sub DefaultLaunch()
   ' Path to the file in the app package to launch
   Dim imageFile = "images\test.png"
   Dim file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile)
   
   If file IsNot Nothing Then
      ' Launch the retrieved file
      Dim success = await Windows.System.Launcher.LaunchFileAsync(file)

      If success Then
         ' File launched
      Else
         ' File launch failed
      End If
   Else
      ' Could not find file
   End If
End Sub
Windows::Foundation::IAsyncAction MainPage::DefaultLaunch()
{
    auto installFolder{ Windows::ApplicationModel::Package::Current().InstalledLocation() };

    Windows::Storage::StorageFile file{ co_await installFolder.GetFileAsync(L"images\\test.png") };

    if (file)
    {
        // Launch the retrieved file
        bool success = co_await Windows::System::Launcher::LaunchFileAsync(file);
        if (success)
        {
            // File launched
        }
        else
        {
            // File launch failed
        }
    }
    else
    {
        // Could not find file
    }
}
void MainPage::DefaultLaunch()
{
   auto installFolder = Windows::ApplicationModel::Package::Current->InstalledLocation;

   concurrency::task<Windows::Storage::StorageFile^getFileOperation(installFolder->GetFileAsync("images\\test.png"));
   getFileOperation.then([](Windows::Storage::StorageFile^ file)
   {
      if (file != nullptr)
      {
         // Launch the retrieved file
         concurrency::task<bool> launchFileOperation(Windows::System::Launcher::LaunchFileAsync(file));
         launchFileOperation.then([](bool success)
         {
            if (success)
            {
               // File launched
            }
            else
            {
               // File launch failed
            }
         });
      }
      else
      {
         // Could not find file
      }
   });
}

打開並啟動

呼叫 Windows.System.Launcher.LaunchFileAsync(IStorageFile, LauncherOptions) 方法,並將 LauncherOptions.DisplayApplicationPicker 設為 true,以啟動使用者從開啟方式對話方塊中選擇的應用程式。

當使用者可能想要選擇特定檔案的預設應用程式以外的應用程式時,我們建議您使用開啟方式對話方塊。 例如,如果您的應用程式允許使用者啟動影像檔案,則預設處理程序可能是檢視器應用程式。 在某些情況下,使用者可能會想要編輯影像,而不是檢視影像。 在 AppBar 或內文功能表中使用開啟方式選項以及替代命令,讓使用者調出開啟方式對話方塊並在這些類型的場景中選擇編輯器應用程式。

the open with dialog for a .png file launch. the dialog contains a checkbox which specifies if the user’s choice should be used for all .png files or just this one .png file. the dialog contains four app options for launching the file and a ‘more options’ link.

async void DefaultLaunch()
{
   // Path to the file in the app package to launch
      string imageFile = @"images\test.png";
      
   var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile);

   if (file != null)
   {
      // Set the option to show the picker
      var options = new Windows.System.LauncherOptions();
      options.DisplayApplicationPicker = true;

      // Launch the retrieved file
      bool success = await Windows.System.Launcher.LaunchFileAsync(file, options);
      if (success)
      {
         // File launched
      }
      else
      {
         // File launch failed
      }
   }
   else
   {
      // Could not find file
   }
}
async Sub DefaultLaunch()

   ' Path to the file in the app package to launch
   Dim imageFile = "images\test.png"

   Dim file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile)

   If file IsNot Nothing Then
      ' Set the option to show the picker
      Dim options = Windows.System.LauncherOptions()
      options.DisplayApplicationPicker = True

      ' Launch the retrieved file
      Dim success = await Windows.System.Launcher.LaunchFileAsync(file)

      If success Then
         ' File launched
      Else
         ' File launch failed
      End If
   Else
      ' Could not find file
   End If
End Sub
Windows::Foundation::IAsyncAction MainPage::DefaultLaunch()
{
    auto installFolder{ Windows::ApplicationModel::Package::Current().InstalledLocation() };

    Windows::Storage::StorageFile file{ co_await installFolder.GetFileAsync(L"images\\test.png") };

    if (file)
    {
        // Set the option to show the picker
        Windows::System::LauncherOptions launchOptions;
        launchOptions.DisplayApplicationPicker(true);

        // Launch the retrieved file
        bool success = co_await Windows::System::Launcher::LaunchFileAsync(file, launchOptions);
        if (success)
        {
            // File launched
        }
        else
        {
            // File launch failed
        }
    }
    else
    {
        // Could not find file
    }
}
void MainPage::DefaultLaunch()
{
   auto installFolder = Windows::ApplicationModel::Package::Current->InstalledLocation;

   concurrency::task<Windows::Storage::StorageFile^> getFileOperation(installFolder->GetFileAsync("images\\test.png"));
   getFileOperation.then([](Windows::Storage::StorageFile^ file)
   {
      if (file != nullptr)
      {
         // Set the option to show the picker
         auto launchOptions = ref new Windows::System::LauncherOptions();
         launchOptions->DisplayApplicationPicker = true;

         // Launch the retrieved file
         concurrency::task<bool> launchFileOperation(Windows::System::Launcher::LaunchFileAsync(file, launchOptions));
         launchFileOperation.then([](bool success)
         {
            if (success)
            {
               // File launched
            }
            else
            {
               // File launch failed
            }
         });
      }
      else
      {
         // Could not find file
      }
   });
}

使用建議的應用程式後援啟動

在某些情況下,使用者可能未安裝應用程式來處理您啟動的檔案。 根據預設,Windows 會藉由提供用戶連結來搜尋市集上適當的應用程式,來處理這些案例。 如果您想向使用者提供在此場景中獲取哪個應用程式的具體建議,您可以透過將該建議與您要啟動的檔案一起傳遞來實現。 為此,請呼叫 Windows.System.Launcher.launchFileAsync(IStorageFile, LauncherOptions) 方法,並將 LauncherOptions.PreferredApplicationPackageFamilyName 設定為應用程式商店中要推薦的應用程式的套件系列名稱。 然後,將 LauncherOptions.PreferredApplicationDisplayName 設定為該應用程式的名稱。 Windows 會使用這項資訊來取代一般選項,以特定選項來搜尋市集中的應用程式,以從市集取得建議的應用程式。

注意

您必須設定這兩個選項來建議應用程式。 設定一個沒有另一個會導致失敗。

the open with dialog for a .contoso file launch. since .contoso does not have a handler installed on the machine the dialog contains an option with the store icon and text which points the user to the correct handler on the store. the dialog also contains a ‘more options’ link'.

async void DefaultLaunch()
{
   // Path to the file in the app package to launch
   string imageFile = @"images\test.contoso";

   // Get the image file from the package's image directory
   var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile);

   if (file != null)
   {
      // Set the recommended app
      var options = new Windows.System.LauncherOptions();
      options.PreferredApplicationPackageFamilyName = "Contoso.FileApp_8wknc82po1e";
      options.PreferredApplicationDisplayName = "Contoso File App";

      // Launch the retrieved file pass in the recommended app
      // in case the user has no apps installed to handle the file
      bool success = await Windows.System.Launcher.LaunchFileAsync(file, options);
      if (success)
      {
         // File launched
      }
      else
      {
         // File launch failed
      }
   }
   else
   {
      // Could not find file
   }
}
async Sub DefaultLaunch()

   ' Path to the file in the app package to launch
   Dim imageFile = "images\test.contoso"

   ' Get the image file from the package's image directory
   Dim file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile)

   If file IsNot Nothing Then
      ' Set the recommended app
      Dim options = Windows.System.LauncherOptions()
      options.PreferredApplicationPackageFamilyName = "Contoso.FileApp_8wknc82po1e";
      options.PreferredApplicationDisplayName = "Contoso File App";

      ' Launch the retrieved file pass in the recommended app
      ' in case the user has no apps installed to handle the file
      Dim success = await Windows.System.Launcher.LaunchFileAsync(file)

      If success Then
         ' File launched
      Else
         ' File launch failed
      End If
   Else
      ' Could not find file
   End If
End Sub
Windows::Foundation::IAsyncAction MainPage::DefaultLaunch()
{
    auto installFolder{ Windows::ApplicationModel::Package::Current().InstalledLocation() };

    Windows::Storage::StorageFile file{ co_await installFolder.GetFileAsync(L"images\\test.png") };

    if (file)
    {
        // Set the recommended app
        Windows::System::LauncherOptions launchOptions;
        launchOptions.PreferredApplicationPackageFamilyName(L"Contoso.FileApp_8wknc82po1e");
        launchOptions.PreferredApplicationDisplayName(L"Contoso File App");

        // Launch the retrieved file, and pass in the recommended app
        // in case the user has no apps installed to handle the file.
        bool success = co_await Windows::System::Launcher::LaunchFileAsync(file, launchOptions);
        if (success)
        {
            // File launched
        }
        else
        {
            // File launch failed
        }
    }
    else
    {
        // Could not find file
    }
}
void MainPage::DefaultLaunch()
{
   auto installFolder = Windows::ApplicationModel::Package::Current->InstalledLocation;

   concurrency::task<Windows::Storage::StorageFile^> getFileOperation(installFolder->GetFileAsync("images\\test.contoso"));
   getFileOperation.then([](Windows::Storage::StorageFile^ file)
   {
      if (file != nullptr)
      {
         // Set the recommended app
         auto launchOptions = ref new Windows::System::LauncherOptions();
         launchOptions->PreferredApplicationPackageFamilyName = "Contoso.FileApp_8wknc82po1e";
         launchOptions->PreferredApplicationDisplayName = "Contoso File App";
         
         // Launch the retrieved file pass, and in the recommended app
         // in case the user has no apps installed to handle the file.
         concurrency::task<bool> launchFileOperation(Windows::System::Launcher::LaunchFileAsync(file, launchOptions));
         launchFileOperation.then([](bool success)
         {
            if (success)
            {
               // File launched
            }
            else
            {
               // File launch failed
            }
         });
      }
      else
      {
         // Could not find file
      }
   });
}

使用所需的剩餘檢視啟動 (僅限 Windows)

呼叫 LaunchFileAsync 的來源應用程式可以要求在檔案啟動後仍留在畫面上。 根據預設,Windows 會嘗試在來源應用程式與處理檔案的目標應用程式之間平均共用所有可用空間。 來源應用程式可以使用 DesiredRemainingView 屬性,向作業系統指出他們偏好其應用程式視窗佔用更多或更少的可用空間。 DesiredRemainingView 也可用於指示來源應用程式在檔案啟動後不需要保留在螢幕上,並且可以完全被目標應用程式取代。 此屬性只會指定呼叫應用程式的慣用視窗大小。 它沒有指定可能同時出現在螢幕上的其他應用程式的行為。

注意

Windows 在決定來源應用程式的最終視窗大小時會考慮多種不同因素,例如來源應用程式的首選項、螢幕上的應用程式數量、螢幕方向等。 藉由設定 DesiredRemainingView,您不保證來源應用程式的特定視窗化行為。

**行動裝置系列:行動裝置系列不支援 **LauncherOptions.DesiredRemainingView

async void DefaultLaunch()
{
   // Path to the file in the app package to launch
   string imageFile = @"images\test.png";
   
   var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile);

   if (file != null)
   {
      // Set the desired remaining view
      var options = new Windows.System.LauncherOptions();
      options.DesiredRemainingView = Windows.UI.ViewManagement.ViewSizePreference.UseLess;

      // Launch the retrieved file
      bool success = await Windows.System.Launcher.LaunchFileAsync(file, options);
      if (success)
      {
         // File launched
      }
      else
      {
         // File launch failed
      }
   }
   else
   {
      // Could not find file
   }
}
Windows::Foundation::IAsyncAction MainPage::DefaultLaunch()
{
    auto installFolder{ Windows::ApplicationModel::Package::Current().InstalledLocation() };

    Windows::Storage::StorageFile file{ co_await installFolder.GetFileAsync(L"images\\test.png") };

    if (file)
    {
        // Set the desired remaining view.
        Windows::System::LauncherOptions launchOptions;
        launchOptions.DesiredRemainingView(Windows::UI::ViewManagement::ViewSizePreference::UseLess);

        // Launch the retrieved file.
        bool success = co_await Windows::System::Launcher::LaunchFileAsync(file, launchOptions);
        if (success)
        {
            // File launched
        }
        else
        {
            // File launch failed
        }
    }
    else
    {
        // Could not find file
    }
}
void MainPage::DefaultLaunch()
{
   auto installFolder = Windows::ApplicationModel::Package::Current->InstalledLocation;

   concurrency::task<Windows::Storage::StorageFile^> getFileOperation(installFolder->GetFileAsync("images\\test.png"));
   getFileOperation.then([](Windows::Storage::StorageFile^ file)
   {
      if (file != nullptr)
      {
         // Set the desired remaining view.
         auto launchOptions = ref new Windows::System::LauncherOptions();
         launchOptions->DesiredRemainingView = Windows::UI::ViewManagement::ViewSizePreference::UseLess;

         // Launch the retrieved file.
         concurrency::task<bool> launchFileOperation(Windows::System::Launcher::LaunchFileAsync(file, launchOptions));
         launchFileOperation.then([](bool success)
         {
            if (success)
            {
               // File launched
            }
            else
            {
               // File launch failed
            }
         });
      }
      else
      {
         // Could not find file
      }
   });
}

備註

您的應用程式無法選取已啟動的應用程式。 用戶決定要啟動哪個應用程式。 使用者可以選擇通用 Windows 平台 (UWP) 應用程式或 Windows 桌面應用程式。

啟動檔案時,您的應用程式必須是前景應用程式,也就是說,使用者必須可以看到它。 這項需求有助於確保使用者保持控制狀態。 若要符合這項需求,請務必將所有檔案啟動直接綁定至應用程式的 UI。 最有可能是,使用者必須一律採取一些動作來起始檔案啟動。

如果操作系統自動執行包含程式碼或指令碼的檔類型,例如.exe、.msi和.js檔案,則您無法啟動包含程式代碼或指令碼的檔類型。 這項限制可保護使用者免於可能修改操作系統的惡意檔案。 您可以使用此方法啟動可包含指令碼的檔案類型 (如果這些檔案類型由隔離指令碼的應用程式執行),例如 .docx 檔案。 Microsoft Word 之類的應用程式會將指令碼保留在.docx 檔案中,使其不修改作業系統。

如果您嘗試啟動受限制的檔案類型,啟動將會失敗,而且將會叫用您的錯誤回呼。 如果您的應用程式處理許多不同類型的檔案,而且您預期會遇到此錯誤,建議您為使用者提供後援體驗。 例如,您可以讓使用者選擇將檔案儲存到桌面,而且他們可以在那裡開啟它。

工作

指導方針

參考