Iniciar o aplicativo padrão para um arquivo
Saiba como iniciar o aplicativo padrão para um arquivo do WinUI, da Plataforma Universal do Windows (UWP) ou de outro aplicativo da área de trabalho. Muitos aplicativos precisam trabalhar com arquivos que não podem lidar sozinhos. Por exemplo, os aplicativos de email recebem uma variedade de tipos de arquivo e precisam de uma maneira de iniciar esses arquivos em seus manipuladores padrão. Estas etapas mostram como usar a API Windows.System.Launcher WinRT (Windows Runtime) para iniciar o manipulador padrão para um arquivo que seu aplicativo não pode manipular sozinho.
APIs importantes
As seguintes APIs são apresentadas neste tópico:
Nota
A menos que seja observado o contrário, todas as APIs do WinRT usadas neste tópico podem ser usadas em aplicativos UWP, aplicativos WinUI e outros aplicativos da área de trabalho. Para ler mais sobre como habilitar seu aplicativo da área de trabalho para trabalhar com APIs do WinRT, consulte Chamar APIs do Windows Runtime em aplicativos da área de trabalho.
Obter o objeto de arquivo
Primeiro, obtenha um objeto Windows.Storage.StorageFile para o arquivo.
Se o arquivo estiver incluído no pacote do seu aplicativo, você poderá usar a propriedade Package.InstalledLocation para obter um objeto Windows.Storage.StorageFolder e o método Windows.Storage.StorageFolder.GetFileAsync para obter o objeto StorageFile.
Se o arquivo estiver em uma pasta conhecida, você poderá usar as propriedades da classe Windows.Storage.KnownFolders para obter um StorageFolder e o método GetFileAsync para obter o objeto StorageFile.
Iniciar o arquivo
O Windows fornece várias opções diferentes para iniciar o manipulador padrão para um arquivo. Essas opções são descritas neste gráfico e nas seções a seguir.
Opção | Método | Descrição |
---|---|---|
Inicialização padrão | LaunchFileAsync(IStorageFile) | Inicie o arquivo especificado com o manipulador padrão. |
Abrir com inicialização | LaunchFileAsync(IStorageFile, LauncherOptions) | Inicie o arquivo especificado permitindo que o usuário escolha o manipulador por meio da caixa de diálogo Abrir com. |
Iniciar com uma opção alternativa de aplicativo recomendado | LaunchFileAsync(IStorageFile, LauncherOptions) | Inicie o arquivo especificado com o manipulador padrão. Se nenhum manipulador estiver instalado no sistema, recomende um aplicativo na loja para o usuário. |
Iniciar com a visualização restante desejada | LaunchFileAsync(IStorageFile, LauncherOptions) (somente Windows) | Inicie o arquivo especificado com o manipulador padrão. Especifique uma preferência para permanecer na tela após a inicialização e solicitar um tamanho de janela específico. LauncherOptions.DesiredRemainingView não é compatível com a família de dispositivos móveis. |
Inicialização padrão
Chame o método Windows.System.LaunchFileAsync(IStorageFile) para executar o aplicativo padrão. Este exemplo usa o método Windows.Storage.StorageFolder.GetFileAsync para iniciar um arquivo de imagem, test.png, incluído 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()
{
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
}
});
}
Abrir com inicialização
Chame o método Windows.System.LaunchFileAsync(IStorageFile, LauncherOptions) com LauncherOptions.DisplayApplicationPicker definido para true para iniciar o aplicativo que o usuário seleciona na caixa de diálogo Abrir com.
Recomendamos que você use a caixa de diálogo Abrir com quando o usuário quiser selecionar um aplicativo diferente do padrão para um arquivo específico. Por exemplo, se o aplicativo permitir que o usuário inicie um arquivo de imagem, o manipulador padrão provavelmente será um aplicativo de visualizador. Em alguns casos, talvez o usuário queira editar a imagem em vez de exibi-la. Use a opção Abrir com juntamente com um comando alternativo na AppBar ou em um menu de contexto para permitir que o usuário abra a caixa de diálogo Abrir com e selecione o aplicativo editor nesses tipos de situação.
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()
{
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
}
});
}
Iniciar com uma alternativa de aplicativo recomendado
Em alguns casos, o usuário pode não ter um aplicativo instalado para lidar com o arquivo que você está iniciando. Por padrão, o Windows lidará com esses casos fornecendo ao usuário um link para pesquisar um aplicativo apropriado na loja. Se você quiser fornecer ao usuário uma recomendação específica para qual aplicativo adquirir nesse cenário, poderá fazer isso passando essa recomendação junto com o arquivo que você está iniciando. Para fazer isso, chame o método Windows.System.Launcher.launchFileAsync(IStorageFile, LauncherOptions) com LauncherOptions.PreferredApplicationPackageFamilyName definido como o nome da família de pacotes do aplicativo na Loja que você deseja recomendar. Em seguida, defina o LauncherOptions.PreferredApplicationDisplayName com o nome desse aplicativo. O Windows usará essas informações para substituir a opção geral para pesquisar um aplicativo na loja por uma opção específica para adquirir o aplicativo recomendado da Loja.
Nota
Você deve definir ambas as opções para recomendar um aplicativo. A configuração de um sem o outro resultará em uma falha.
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
}
}
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
}
});
}
Iniciar com uma Visualização Restante Desejada (somente UWP)
Os aplicativos de origem que chamam LaunchFileAsync podem solicitar que eles permaneçam na tela após a inicialização de um arquivo. Por padrão, o Windows tenta compartilhar todo o espaço disponível igualmente entre o aplicativo de origem e o aplicativo de destino que manipula o arquivo. Os aplicativos de origem podem usar a propriedade DesiredRemainingView para indicar ao sistema operacional que preferem que a janela do aplicativo assuma mais ou menos do espaço disponível. DesiredRemainingView também pode ser usado para indicar que o aplicativo de origem não precisa permanecer na tela após a inicialização do arquivo e pode ser completamente substituído pelo aplicativo de destino. Essa propriedade especifica apenas o tamanho de janela preferencial do aplicativo de chamada. Ele não especifica o comportamento de outros aplicativos que também podem estar na tela ao mesmo tempo.
Nota
O Windows leva em conta vários fatores diferentes quando determina o tamanho final da janela do aplicativo de origem, por exemplo, a preferência do aplicativo de origem, o número de aplicativos na tela, a orientação da tela e assim por diante. Ao definir DesiredRemainingView, não é garantido um comportamento de janela específico para o aplicativo de origem.
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
}
});
}
Observações
Seu aplicativo não pode selecionar o aplicativo que é executado. O usuário determina qual aplicativo é iniciado. O usuário pode selecionar um aplicativo UWP ou um aplicativo da área de trabalho do Windows.
Ao iniciar um arquivo, seu aplicativo deve ser o aplicativo em primeiro plano, ou seja, ele deve estar visível para o usuário. Esse requisito ajuda a garantir que o usuário permaneça no controle. Para atender a esse requisito, certifique-se de vincular todas as inicializações de arquivo diretamente à interface do usuário do seu aplicativo. Provavelmente, o usuário deve sempre executar alguma ação para iniciar uma inicialização de arquivo.
Você não poderá iniciar tipos de arquivo que contenham código ou script se eles forem executados automaticamente pelo sistema operacional, como, .exe, .msie arquivos .js. Essa restrição protege os usuários contra arquivos potencialmente mal-intencionados que podem modificar o sistema operacional. Você pode usar esse método para iniciar tipos de arquivo que podem conter script se forem executados por um aplicativo que isola o script, como .docx arquivos. Aplicativos como o Microsoft Word, mantêm o script nos arquivos .docx de modificar o sistema operacional.
Se você tentar abrir um arquivo de tipo restrito, a execução falhará, e o callback de erro será invocado. Se seu aplicativo manipular muitos tipos diferentes de arquivos e você espera encontrar esse erro, recomendamos que você forneça uma experiência alternativa ao usuário. Por exemplo, você pode dar ao usuário uma opção para salvar o arquivo na área de trabalho e eles podem abri-lo lá.
Conteúdo relacionado
- Abrir o aplicativo padrão para um URI
- Manipular ativação de arquivo
- Windows.System.Launcher.LaunchFileAsync
Windows developer