Share via


Launcher.LaunchFileAsync Método

Definição

Sobrecargas

LaunchFileAsync(IStorageFile)

Inicia o aplicativo padrão associado ao arquivo especificado.

LaunchFileAsync(IStorageFile, LauncherOptions)

Inicia o aplicativo padrão associado ao arquivo especificado, usando as opções especificadas.

LaunchFileAsync(IStorageFile)

Inicia o aplicativo padrão associado ao arquivo especificado.

public:
 static IAsyncOperation<bool> ^ LaunchFileAsync(IStorageFile ^ file);
/// [Windows.Foundation.Metadata.Overload("LaunchFileAsync")]
 static IAsyncOperation<bool> LaunchFileAsync(IStorageFile const& file);
[Windows.Foundation.Metadata.Overload("LaunchFileAsync")]
public static IAsyncOperation<bool> LaunchFileAsync(IStorageFile file);
function launchFileAsync(file)
Public Shared Function LaunchFileAsync (file As IStorageFile) As IAsyncOperation(Of Boolean)

Parâmetros

file
IStorageFile

O arquivo.

Retornos

A operação de inicialização.

Atributos

Exemplos

Este exemplo usa LaunchFileAsync(IStorageFile) para iniciar um arquivo contido no pacote do aplicativo.

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
   }
}
Windows::Foundation::IAsyncAction MainPage::DefaultLaunch()
{
    // Get the app's installation folder.
    Windows::Storage::StorageFolder installFolder{ Windows::ApplicationModel::Package::Current().InstalledLocation() };

    Windows::Storage::StorageFile file{ co_await installFolder.GetFileAsync(L"Assets\\LockScreenLogo.scale-200.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
    {
        // Couldn't 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
      }
   });
}
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

Comentários

O aplicativo de chamada deve estar visível para o usuário quando a API é invocada.

Essa API deve ser chamada de um thread ASTA (também conhecido como thread de interface do usuário).

Essa API também impõe várias restrições sobre quais tipos de arquivos ela pode iniciar. Muitos tipos de arquivo que contêm código executável, por exemplo, arquivos .exe, .msi e .js, são impedidos de iniciar. Essa restrição protege os usuários contra arquivos potencialmente mal-intencionados que podem modificar o sistema.

Quando a inicialização falha por qualquer um dos motivos acima, a API é bem-sucedida e retorna FALSE de sua operação assíncrona. Como não tem a capacidade de consultar se as restrições acima se aplicam à inicialização atual, o aplicativo de chamada não deve assumir que a inicialização foi bem-sucedida e deve fornecer mecanismo de fallback caso tenha falhado. Uma solução possível seria pedir ao usuário para salvar o arquivo e direcionar o usuário para abri-lo na área de trabalho.

Para permitir que o usuário escolha um aplicativo em vez de iniciar o aplicativo padrão, defina a propriedade LauncherOptions.DisplayApplicationPicker .

Para exibir um aviso de que o arquivo é potencialmente inseguro, defina a propriedade LauncherOptions.TreatAsUntrusted .

O arquivo é passado para o aplicativo associado. Se o aplicativo associado for um aplicativo da área de trabalho, o arquivo será passado usando mecanismos de execução de shell.

Confira também

Aplica-se a

LaunchFileAsync(IStorageFile, LauncherOptions)

Inicia o aplicativo padrão associado ao arquivo especificado, usando as opções especificadas.

public:
 static IAsyncOperation<bool> ^ LaunchFileAsync(IStorageFile ^ file, LauncherOptions ^ options);
/// [Windows.Foundation.Metadata.Overload("LaunchFileWithOptionsAsync")]
 static IAsyncOperation<bool> LaunchFileAsync(IStorageFile const& file, LauncherOptions const& options);
[Windows.Foundation.Metadata.Overload("LaunchFileWithOptionsAsync")]
public static IAsyncOperation<bool> LaunchFileAsync(IStorageFile file, LauncherOptions options);
function launchFileAsync(file, options)
Public Shared Function LaunchFileAsync (file As IStorageFile, options As LauncherOptions) As IAsyncOperation(Of Boolean)

Parâmetros

file
IStorageFile

O arquivo.

options
LauncherOptions

As opções de inicialização do aplicativo.

Retornos

A operação de inicialização.

Atributos

Exemplos

Chame o método [Launcher.LaunchFileAsync(IStorageFile, LauncherOptions) com LauncherOptions.DisplayApplicationPicker definido como true para iniciar o aplicativo que o usuário seleciona para o arquivo na caixa de diálogo Abrir com .

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
   }
}
Windows::Foundation::IAsyncAction MainPage::DefaultLaunch()
{
    // Get the app's installation folder.
    Windows::Storage::StorageFolder installFolder{ Windows::ApplicationModel::Package::Current().InstalledLocation() };

    Windows::Storage::StorageFile file{ co_await installFolder.GetFileAsync(L"Assets\\LockScreenLogo.scale-200.png") };

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

        // Launch the retrieved file.
        bool success{ co_await Windows::System::Launcher::LaunchFileAsync(file, launcherOptions) };
        if (success)
        {
            // File launched.
        }
        else
        {
            // File launch failed.
        }
    }
    else
    {
        // Couldn't 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
      }
   });
}
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, options)

      If success Then
         ' File launched
      Else
         ' File launch failed
      End If
   Else
      ' Could not find file
   End If
End Sub

Comentários

O aplicativo de chamada deve estar visível para o usuário quando a API é invocada.

Essa API deve ser chamada de dentro de um thread do ASTA (também conhecido como thread de interface do usuário).

Essa API também impõe várias restrições sobre quais tipos de arquivos ela pode iniciar. Muitos tipos de arquivo que contêm código executável, por exemplo, arquivos .exe, .msi e .js, são impedidos de iniciar. Essa restrição protege os usuários contra arquivos potencialmente mal-intencionados que podem modificar o sistema.

Quando a inicialização falha por qualquer um dos motivos acima, a API é bem-sucedida e retorna FALSE de sua operação assíncrona. Como não tem a capacidade de consultar se as restrições acima se aplicam à inicialização atual, o aplicativo de chamada não deve assumir que a inicialização foi bem-sucedida e deve fornecer mecanismo de fallback caso tenha falhado. Uma solução possível seria pedir ao usuário para salvar o arquivo e direcionar o usuário para abri-lo na área de trabalho.

Para permitir que o usuário escolha um aplicativo em vez de iniciar o aplicativo padrão, defina a propriedade LauncherOptions.DisplayApplicationPicker .

Para exibir um aviso de que o arquivo é potencialmente inseguro, defina a propriedade LauncherOptions.TreatAsUntrusted .

O arquivo é passado para o aplicativo associado. Se o aplicativo associado for um aplicativo da área de trabalho, o arquivo será passado usando mecanismos de execução de shell.

Confira também

Aplica-se a