.NET 앱에서 interop API 호출

C# 데스크톱 애플리케이션 개발자는 .NET에서 여러 상호 운용성 함수와 Windows 런타임(WinRT) COM 상호 운용성 인터페이스를 나타내는 C# interop 클래스를 사용할 수 있습니다. 여기에는 IWindowNative, IInitializeWithWindow, GetWindowIdFromWindow 함수 등을 나타내는 C# 클래스가 포함됩니다.

이 항목에서는 사용 가능한 C# interop 클래스를 나열하고 사용 방법을 보여줍니다. 항목 마지막에 있는 백그라운드 섹션에서는 이전 버전의 .NET에서 interop 인터페이스가 사용된 방식과 변경된 이유에 대해 설명합니다.

C# interop 클래스를 사용하도록 .NET 데스크톱 프로젝트 구성

다음 섹션에 나열된 C# interop 클래스(사용 가능한 C# interop 클래스)는 .NET에서 Windows 앱 SDK의 일부로서 또는 특정 대상 프레임워크 모니커를 사용하여 사용할 수 있으며, 이는 나중에 살펴보도록 하겠습니다.

WinUI 3 C# 데스크톱 프로젝트에서

Visual Studio에서 새 WinUI 3 프로젝트를 만들면(첫 번째 WinUI 3 프로젝트 만들기 참조) 프로젝트가 이미 구성되며 모든 C# interop 클래스를 즉시 사용할 수 있습니다.

다른 C# 데스크톱 프로젝트 형식(WPF 또는 WinForms)에서

WPF(Windows Presentation Foundation) 또는 Windows Forms(WinForms)와 같은 다른 .NET 데스크톱 프로젝트 형식의 경우 C# interop 클래스에 액세스하려면 먼저 프로젝트를 구성해야 합니다. 아래 나열된 첫 번째 클래스 세트의 경우 Windows 앱 SDK를 참조해야 합니다. 두 번째 세트의 경우 다음과 같이 Windows 10 버전 1809 이상을 대상으로 하는 대상 프레임워크 모니커를 구성해야 합니다.

  1. C# .NET 데스크톱 프로젝트용 프로젝트 파일을 엽니다.

  2. .csproj 파일에서 TargetFramework 요소를 수정하여 특정 .NET 및 Windows SDK 버전을 대상으로 합니다. 예를 들어, 다음 요소는 Windows 10, 버전 2004를 대상으로 하는 .NET 6 프로젝트에 적합합니다.

    <PropertyGroup>
      <TargetFramework>net6.0-windows10.0.19041.0</TargetFramework>
    </PropertyGroup>
    

지원되는 다른 값 목록을 포함한 자세한 내용은 대상 프레임워크 Moniker 옵션 사용을 참조하세요.

사용 가능한 C# interop 클래스

참고

아래 클래스에는 .NET 6 SDK 이상이 필요합니다.

다음은 기본 interop 함수 또는 WinRT COM interop 인터페이스에서 매핑된 사용 가능한 C# interop 클래스입니다. 나열된 각 클래스는 기본 interop API의 기능/메서드를 구현하며, 매개 변수 및 반환 값에 대한 형식 안전 래퍼를 제공합니다. 예를 들어 Windows.ApplicationModel.DataTransfer.DragDrop.Core.DragDropManagerInterop.GetForWindowIntPtr 창 핸들(HWND) 매개 변수가 필요하고 CoreDragDropManager 개체를 반환합니다. 아래의 모든 C# interop 클래스 및 관련 메서드는 정적입니다.

Windows 앱 SDK의 일부로 사용 가능

Microsoft.UI.Win32Interop 클래스는 아래 표의 C# interop 메서드를 구현합니다. 코드 예제는 앱 창 관리를 참조하세요.

Interop 함수 C# interop 메서드
GetDisplayIdFromMonitor (Microsoft.UI) DisplayId Win32Interop.GetDisplayIdFromMonitor(IntPtr hmonitor)
GetIconFromIconId (Microsoft.UI) IntPtr Win32Interop.GetIconFromIconId(IconId iconId)
GetIconIdFromIcon (Microsoft.UI) IconId Win32Interop.GetIconIdFromIcon(IntPtr hicon)
GetMonitorFromDisplayId (Microsoft.UI) IntPtr Win32Interop.GetMonitorFromDisplayId(DisplayId displayId)
GetWindowFromWindowId (Microsoft.UI) IntPtr Win32Interop.GetWindowFromWindowId(WindowId windowId)
GetWindowIdFromWindow (Microsoft.UI) WindowId Win32Interop.GetWindowIdFromWindow(IntPtr hwnd)

대상 프레임워크 Moniker를 통해 사용 가능

WinRT COM interop 인터페이스 C# interop 클래스
IAccountsSettingsPaneInterop (Windows.UI.ApplicationSettings) AccountsSettingsPaneInterop
IDisplayInformationStaticsInterop TFM net6.0-windows10.0.22621.0 및 .NET 6.0.7에 도입되었습니다.

(Windows.Graphics.Display) DisplayInformationInterop
IDragDropManagerInterop (Windows.ApplicationModel.DataTransfer.DragDrop.Core) DragDropManagerInterop
IInitializeWithWindow (WinRT.Interop) InitializeWithWindow
IInputPaneInterop (Windows.UI.ViewManagement) InputPaneInterop
IPlayToManagerInterop (Windows.Media.PlayTo) PlayToManagerInterop
IPrintManagerInterop (Windows.Graphics.Printing) PrintManagerInterop
IRadialControllerConfigurationInterop (Windows.UI.Input) RadialControllerConfigurationInterop
IRadialControllerIndependentInputSourceInterop (Windows.UI.Input.Core) RadialControllerIndependentInputSourceInterop
IRadialControllerInterop (Windows.UI.Input) RadialControllerInterop
ISpatialInteractionManagerInterop (Windows.UI.Input.Spatial) SpatialInteractionManagerInterop
ISystemMediaTransportControlsInterop (Windows.Media) SystemMediaTransportControlsInterop
IUIViewSettingsInterop (Windows.UI.ViewManagement) UIViewSettingsInterop
IUserConsentVerifierInterop (Windows.Security.Credentials.UI) UserConsentVerifierInterop
IWebAuthenticationCoreManagerInterop (Windows.Security.Authentication.Web.Core) WebAuthenticationCoreManagerInterop
IWindowNative WinUI 3 전용

(WinRT.Interop) WindowNative

WPF 및 WinForms에 대한 대안 사항은 창 핸들(HWND) 검색을 참조하세요.

코드 예

이 코드 예제에서는 WinUI 3 애플리케이션에서 두 개의 C# interop 클래스를 사용하는 방법을 확인할 수 있습니다(첫 번째 WinUI 3 프로젝트 만들기 참조). 예시 시나리오는 Windows.Storage.Pickers.FolderPicker를 표시하는 것입니다. 하지만 데스크톱 앱에서 선택기를 표시하기 전, 소유자 창의 핸들(HWND)로 초기화해야 합니다.

  1. IWindowNative WinRT COM interop 인터페이스를 사용하여 창 핸들(HWND)을 얻을 수 있습니다. 그리고 (이전 섹션의 표 참조) 해당 인터페이스는 WinRT.Interop.WindowNative C# interop 클래스로 표시됩니다. 여기에서 this 개체는 주 창 코드 숨김 파일의 Microsoft.UI.Xaml.Window 개체에 대한 참조입니다.
  2. 소유자 창으로 UI를 초기화하려면 IInitializeWithWindow WinRT COM interop 인터페이스를 사용합니다. 그리고 이 인터페이스는 WinRT.Interop.InitializeWithWindow C# interop 클래스로 표시됩니다.
private async void myButton_Click(object sender, RoutedEventArgs e)
{
    // Create a folder picker.
    var folderPicker = new Windows.Storage.Pickers.FolderPicker();

    // 1. Retrieve the window handle (HWND) of the current WinUI 3 window.
    var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(this);

    // 2. Initialize the folder picker with the window handle (HWND).
    WinRT.Interop.InitializeWithWindow.Initialize(folderPicker, hWnd);

    // Use the folder picker as usual.
    folderPicker.FileTypeFilter.Add("*");
    var folder = await folderPicker.PickSingleFolderAsync();
}

또한 창 핸들(HWND) 검색CoreWindow에 의존하는 WinRT UI 개체 표시를 참조하세요.

백그라운드

이전 버전의 .NET Framework 및 .NET Core에는 WinRT에 대한 기본 제공 지식이 포함되어 있었습니다. 이전 버전에서는 ComImport 속성을 사용하여 C#에서 직접 interop 인터페이스를 정의한 다음, 프로젝션된 클래스를 해당 interop 인터페이스로 직접 캐스팅할 수 있었습니다.

WinRT는 Windows 전용 기술입니다. .NET의 이식성 및 효율성 목표를 지원하기 위해 C# 컴파일러 및 .NET 런타임에서 WinRT 프로젝션 지원을 해제하고 C#/WinRT 도구 키트로 이동했습니다(WinRT에 대한 기본 제공 지원이 .NET에서 제거됨 참조).

ComImport 기술은 IUnknown 기반 interop 인터페이스에서 계속 작동하지만 WinRT와 상호 운용하는 데 사용되는 IInspectable 기반 인터페이스에서는 더 이상 작동하지 않습니다.

따라서 .NET에서는 이 항목에 설명된 C# interop 클래스를 대신 사용할 수 있습니다.

문제 해결 및 알려진 문제

현재 C# interop 클래스에 대해 알려진 문제가 없습니다. 피드백을 제공하거나 다른 문제를 보고하려면 피드백을 기존 문제에 추가하거나 WindowsAppSDK GitHub 리포지토리에서 새 문제를 제출하세요.