Iniciar o app padrão para um arquivo
APIs importantes
Aprenda como iniciar o app padrão para um arquivo. Muitos aplicativos precisam funcionar com arquivos que eles não podem manipular sozinhos. Por exemplo, os aplicativos de email recebem uma variedade de tipos de arquivo e precisam de alguma maneira iniciá-los em seus manipuladores padrão. Essas etapas mostram como usar a API Windows.System.Launcher para iniciar o manipulador padrão para um arquivo que seu aplicativo não pode manipular sozinho.
Obter o objeto de arquivo
Primeiro, obtenha um objeto Windows.Storage.StorageFile para o arquivo.
Se o arquivo estiver incluído no pacote do 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, é possível usar as propriedades da classe Windows.Storage.KnownFolders para obter uma 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 estão descritas neste gráfico e nas seções que seguem.
Opção | Método | Descrição |
---|---|---|
Início padrão | LaunchFileAsync(IStorageFile) | Inicie o arquivo especificado com o manipulador padrão. |
Início com Abrir com | LaunchFileAsync(IStorageFile, LauncherOptions) | Inicie o arquivo especificado deixando que o usuário escolha o manipulador na caixa de diálogo Abrir com. |
Iniciar com um fallback do aplicativo recomendado | LaunchFileAsync(IStorageFile, LauncherOptions) | Inicie o arquivo especificado com o manipulador padrão. Se nenhum manipulador estiver instalado no sistema, recomende ao usuário um aplicativo na Loja. |
Iniciar com um modo de exibição restante desejado | 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 solicite um tamanho específico de janela. LauncherOptions.DesiredRemainingView não é compatível na família de dispositivos móveis. |
Início padrão
Chame o método Windows.System.Launcher.LaunchFileAsync(IStorageFile) para inicializar o aplicativo padrão. Este exemplo usa o método Windows.Storage.StorageFolder.GetFileAsync para iniciar um arquivo de imagem, test.png, que está 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
}
}
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
}
});
}
Início com Abrir com
Chame o método Windows.System.Launcher.LaunchFileAsync(IStorageFile, LauncherOptions) com LauncherOptions.DisplayApplicationPicker configurado para true para inicializar o aplicativo que o usuário selecionar na caixa de diálogo Abrir com.
Recomendamos que use a caixa de diálogo Abrir com quando o usuário quiser selecionar um aplicativo diferente do padrão para um determinado tipo de arquivo. Por exemplo, se o seu aplicativo permitir que o usuário inicie um arquivo de imagem, provavelmente o manipulador padrão será um aplicativo de visualização. Em alguns casos, o usuário pode querer editar a imagem em vez de visualizá-la. Use a opção Abrir com junto com um comando alternativo no controle 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 de edição nesses tipos de cenário.
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
}
});
}
Iniciar com um fallback do aplicativo recomendado
Em alguns casos, pode ser que o usuário não tenha um aplicativo instalado para manipular o arquivo que você está iniciando. Por padrão, nesses casos, o Windows oferece ao usuário um link para pesquisar o aplicativo apropriado na Loja. Se você quiser, poderá fazer uma recomendação específica sobre qual aplicativo deve ser adquirido nesse cenário, transmitindo tal 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 para o nome da família do pacote do aplicativo na Loja que você deseja recomendar. Em seguida, defina LauncherOptions.PreferredApplicationDisplayName como o nome desse aplicativo. O Windows usará essas informações para substituir a opção geral de pesquisar um aplicativo na Loja por uma opção específica para adquirir o aplicativo recomendado na Loja.
Observação
Você deve definir essas duas opções para recomendar um aplicativo. Se você definir uma opção sem a outra, haverá 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
}
}
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
}
});
}
Iniciar com um Modo de Exibição Restante Desejado (somente Windows)
Aplicativos de origem que chamam LaunchFileAsync podem solicitar que permaneçam na tela após a inicialização de um arquivo. Por padrão, o Windows tenta dividir todo o espaço disponível igualmente entre o aplicativo de origem e o aplicativo de destino que manipula o arquivo. Aplicativos de origem podem usar a propriedade DesiredRemainingView para indicar ao sistema operacional que eles preferem que sua janela de aplicativo ocupe mais ou menos espaço disponível. DesiredRemainingView também pode ser usado para indicar que o aplicativo de origem não precisa permanecer na tela depois da inicialização do arquivo e pode ser completamente substituído pelo aplicativo de destino. Esta propriedade especifica somente o tamanho da janela preferido do aplicativo de chamada. Ele não especifica o comportamento de outros aplicativos que podem acontecer de também estar na tela ao mesmo tempo.
Observação
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. Definindo DesiredRemainingView, você não garante um comportamento de janelas específico para o aplicativo de origem.
**Família de dispositivos móveis: **LauncherOptions.DesiredRemainingView não tem suporte na família de dispositivos móveis.
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
}
});
}
Comentários
Seu aplicativo não pode selecionar o aplicativo que foi iniciado. O usuário determina o aplicativo que é iniciado. O usuário pode selecionar um aplicativo da Plataforma Universal do Windows (UWP) ou um aplicativo da área de trabalho do Windows.
Ao iniciar um arquivo, seu aplicativo tem que estar em primeiro plano, ou seja, visível para o usuário. Essa exigência ajuda a garantir que o usuário permaneça no controle. Para que essa exigência seja atendida, você deve vincular todas as inicializações de arquivo diretamente à interface do usuário do aplicativo. O mais provável é que o usuário execute alguma ação para iniciar um arquivo.
Você não pode iniciar tipos de arquivos com código ou script que são executados automaticamente pelo sistema operacional, como os arquivos .exe, .msi e .js. Essa restrição protege os usuários contra arquivos possivelmente maliciosos que podem modificar o sistema operacional. Você pode usar esse método para iniciar arquivos que contenham script se eles forem executados por um aplicativo que isole o script, como os arquivos .docx. Aplicativos como o Microsoft Word impedem que o script nos arquivos .docx modifique o sistema operacional.
Quando você tenta iniciar um tipo de arquivo restrito, há falha na inicialização e o retorno de chamada de erro é invocado. Quando o seu aplicativo manipula vários tipos de arquivos diferentes e você espera obter esse erro, nós recomendamos que você ofereça uma experiência de fallback ao usuário. Por exemplo, você pode dar ao usuário a opção de salvar o arquivo na área de trabalho para abri-lo de lá.
Tópicos relacionados
Tarefas
Diretrizes
Referência
Comentários
https://aka.ms/ContentUserFeedback.
Em breve: Ao longo de 2024, eliminaremos os problemas do GitHub como o mecanismo de comentários para conteúdo e o substituiremos por um novo sistema de comentários. Para obter mais informações, consulteEnviar e exibir comentários de