다음을 통해 공유


.NET 앱에서 interop API 호출

C# 데스크톱 애플리케이션 개발자는 .NET에서 여러 상호 운용성 함수 및 WinRT(Windows 런타임) 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) WinForms(Windows Forms) 같은 다른 .NET 데스크톱 프로젝트 형식의 경우 C# interop 클래스에 액세스하려면 프로젝트를 구성해야 합니다. 아래에 나열된 첫 번째 클래스 집합의 경우 Windows 앱 SDK참조해야 합니다. 두 번째 집합의 경우 다음과 같이 Windows 10 버전 1809 이상을 대상으로 하는 대상 프레임워크 모니커 구성해야 합니다.

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

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

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

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

사용 가능한 C# interop 클래스

Note

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

다음은 기본 interop 함수 또는 WinRT COM interop 인터페이스에서 매핑된 사용 가능한 C# interop 클래스입니다. 나열된 각 클래스는 기본 interop API의 함수/메서드를 구현하고 매개 변수 및 반환 값에 대해 형식이 안전한 래퍼를 제공합니다. 예를 들어 Windows.ApplicationModel.DataTransfer.DragDrop.Core.DragDropManagerInterop.GetForWindow 에는 IntPtr 창 핸들(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)

대상 프레임워크 모니커를 통해 사용 가능

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 개체를표시를 참조하세요.

Background

이전 버전의 .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 리포지토리새 문제를 제출합니다.