파일에 대한 기본 앱 시작

중요 API

파일에 대한 기본 앱을 시작하는 방법을 알아봅니다. 상당수의 앱은 단독으로 처리할 수 없는 파일로 작업해야 합니다. 그 예로 이메일 앱은 다양한 파일 형식을 수신하며, 기본 처리기에서 이 파일들을 시작할 방법이 필요합니다. 다음 단계에서는 Windows.System.Launcher API를 사용하여 앱이 단독으로 처리할 수 없는 파일에 대해 기본 처리기를 시작하는 방법을 보여줍니다.

파일 개체 가져오기

먼저 해당 파일에 대한 Windows.Storage.StorageFile 개체를 가져오세요.

파일이 앱용 패키지에 포함되어 있다면 Package.InstalledLocation 속성을 사용하여 Windows.Storage.StorageFolder 개체 및 Windows.Storage.StorageFolder.GetFileAsync 메서드를 가져옴으로써 StorageFile 개체를 확보할 수 있습니다.

파일이 알려진 폴더에 있다면 Windows.Storage.KnownFolders 클래스의 속성을 사용하여 StorageFolderGetFileAsync 메서드를 가져옴으로써 StorageFile 개체를 확보할 수 있습니다.

파일 시작하기

Windows는 파일의 기본 처리기를 시작하기 위한 여러 가지 옵션을 제공합니다. 이 옵션들은 이 차트와 다음 섹션에 설명되어 있습니다.

옵션 메서드 설명
기본 시작 LaunchFileAsync(IStorageFile) 기본 처리기로 지정된 파일을 시작하세요.
시작과 함께 열기 LaunchFileAsync(IStorageFile, LauncherOptions) 지정한 파일을 시작하여 사용자가 "대화 상자로 열기"를 통해 처리기를 선택할 수 있게 하세요.
권장 앱 폴백으로 시작 LaunchFileAsync(IStorageFile, LauncherOptions) 기본 처리기로 지정된 파일을 시작하세요. 시스템에 처리기가 설치되어 있지 않다면 스토어의 앱을 사용자에게 추천하세요.
원하는 잔여 뷰로 시작하기 LaunchFileAsync(IStorageFile, LauncherOptions)(Windows만 해당) 기본 처리기로 지정된 파일을 시작하세요. 시작 후 화면에 계속 나타나도록 기본 설정을 지정하고 구체적인 창 크기를 요청하세요. 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
      }
   });
}

시작과 함께 열기

사용자가 열기 대화 상자에서 선택한 앱을 시작하려면 true로 설정된 LauncherOptions.DisplayApplicationPicker를 사용하여 Windows.System.Launcher.LaunchFileAsync(IStorageFile, LauncherOptions) 메서드를 호출하세요.

사용자가 특정 파일의 기본값이 아닌 다른 앱을 선택해야 하는 경우에는 열기 대화 상자를 사용하는 것이 좋습니다. 그 예로 앱에서 사용자가 이미지 파일을 시작할 수 있도록 허용하는 경우, 뷰어 앱이 기본 처리기가 될 가능성이 높습니다. 경우에 따라서는 사용자가 이미지를 보지 않는 대신 편집해야 할 수도 있습니다. 사용자가 열기 대화 상자를 띄우고 이러한 유형의 시나리오에서 편집기 앱을 선택할 수 있게 하려면 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는 기본적으로 스토어에서 적절한 앱을 검색할 수 있는 링크를 사용자에게 제공함으로써 이러한 사례를 처리합니다. 이 시나리오에서 가져올 앱에 대한 특정 권장 사항을 사용자에게 제공하려는 경우, 시작할 파일과 함께 해당 권장 사항을 전달하여 이를 수행할 수 있습니다. 이렇게 하려면 추천하려는 스토어에서 앱의 패키지 제품군 이름으로 설정된 LauncherOptions.PreferredApplicationPackageFamilyName으로 Windows.System.Launcher.launchFileAsync(IStorageFile, LauncherOptions) 메서드를 호출하세요. 그런 다음 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
      }
   });
}

설명

앱에서는 시작할 앱을 선택할 수 없습니다. 사용자가 어떤 앱을 시작할지 결정해야 합니다. 사용자는 UWP(유니버설 Windows 플랫폼) 앱 또는 Windows 데스크톱 앱 중 하나를 선택할 수 있습니다.

파일을 시작할 때는 사용자의 앱이 포그라운드 앱이어야 합니다. 다시 말해서, 앱이 사용자에게 표시되어야 합니다. 이 요건은 사용자가 제어 권한을 유지하는 데 도움이 됩니다. 이 요건을 충족하려면 모든 파일 시작을 앱의 UI에 직접 연결해야 합니다. 대부분의 경우 사용자는 파일 시작을 개시할 때마다 몇 가지 조치를 취해야 합니다.

코드 또는 스크립트가 담긴 파일 형식(예: .exe, .msi, .js 파일)이 운영 체제에서 자동으로 실행되는 경우에는 그러한 파일 형식을 시작할 수 없습니다. 이 제한은 운영 체제를 변형시킬 수 있는 잠재적인 악성 파일로부터 사용자를 보호합니다. 이 메서드를 사용하면 스크립트가 담길 수 있는 파일 형식이 스크립트(예: .docx 파일)를 분리하는 앱에서 실행될 경우, 그러한 파일 형식을 시작할 수 있습니다. Microsoft Word 등의 앱은 .docx 파일 속 스크립트가 운영 체제를 변형시키지 못하게 합니다.

제한된 파일 형식을 시작하려고 하면 시작이 실패하고 오류 콜백이 호출됩니다. 앱에서 다양한 여러 가지 형식의 파일을 처리하고 이러한 오류가 발생할 것으로 예상되는 경우, 사용자에게 대체 환경을 제공하는 것이 좋습니다. 그 예로 바탕 화면에 파일을 저장할 수 있는 옵션을 사용자에게 제공하면 바탕 화면에서 파일을 열 수 있습니다.

작업

지침

참조