Microsoft MVP성태의 닷넷 이야기
.NET Framework: 991. .NET 5 응용 프로그램에서 WinRT API 호출 [링크 복사], [링크+제목 복사]
조회: 10059
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 10개 있습니다.)
.NET Framework: 388. 일반 닷넷 프로젝트에서 WinRT API를 호출하는 방법
; https://www.sysnet.pe.kr/2/0/1508

.NET Framework: 613. 윈도우 데스크톱 응용 프로그램(예: Console)에서 알림 메시지(Toast notifications) 띄우기
; https://www.sysnet.pe.kr/2/0/11073

.NET Framework: 623. C# - PeerFinder를 이용한 Wi-Fi Direct 데이터 통신 예제
; https://www.sysnet.pe.kr/2/0/11106

.NET Framework: 678. 데스크톱 윈도우 응용 프로그램에서 UWP 라이브러리를 이용한 비디오 장치 열람하는 방법
; https://www.sysnet.pe.kr/2/0/11284

.NET Framework: 715. C# - Windows 10 운영체제의 데스크톱 앱에서 TTS(SpeechSynthesizer) 사용하는 방법
; https://www.sysnet.pe.kr/2/0/11412

.NET Framework: 722. C# - Windows 10 운영체제의 데스크톱 앱에서 음성인식(SpeechRecognizer) 사용하는 방법
; https://www.sysnet.pe.kr/2/0/11420

.NET Framework: 804. WPF(또는 WinForm)에서 UWP UI 구성 요소 사용하는 방법
; https://www.sysnet.pe.kr/2/0/11799

.NET Framework: 852. WPF/WinForm에서 UWP의 기능을 이용해 Bluetooth 기기와 Pairing하는 방법
; https://www.sysnet.pe.kr/2/0/12001

.NET Framework: 991. .NET 5 응용 프로그램에서 WinRT API 호출
; https://www.sysnet.pe.kr/2/0/12470

닷넷: 2157. C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어
; https://www.sysnet.pe.kr/2/0/13438




.NET 5 응용 프로그램에서 WinRT API 호출

이번 글은 다음의 내용에 대한 실습입니다.

Calling Windows APIs in .NET5
; https://blogs.windows.com/windowsdeveloper/2020/09/03/calling-windows-apis-in-net5/




예전에도 이에 대한 소개를 몇 번 했는데요,

일반 닷넷 프로젝트에서 WinRT API를 호출하는 방법
; https://www.sysnet.pe.kr/2/0/1508

윈도우 데스크톱 응용 프로그램(예: Console)에서 알림 메시지(Toast notifications) 띄우기
; https://www.sysnet.pe.kr/2/0/11073

데스크톱 윈도우 응용 프로그램에서 UWP 라이브러리를 이용한 비디오 장치 열람하는 방법
; https://www.sysnet.pe.kr/2/0/11284

.NET 5의 경우 Preview 8부터 새로운 TFM(Target Framework Monikers)을 추가해 별도의 NuGet 라이브러리 참조 없이 연동하게 만들었다고 합니다.

간단하게 실습을 해보면, .NET 5 대상의 Windows Forms 프로젝트를 만든 후, TargetFramework에 다음과 같이 "net5.0-windows10..." TFM을 지정하면 됩니다.

<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net5.0-windows10.0.17763.0</TargetFramework>
    <UseWindowsForms>true</UseWindowsForms>
  </PropertyGroup>

</Project>

TFM에 지정 가능한 버전은 (Windows 10의 최신 버전이 19041이므로) 3가지입니다.

  • 10.0.17763.0
  • 10.0.18362.0
  • 10.0.19041.0

이렇게 TFM을 바꾸면 프로젝트의 의존성에 "Microsoft.Windows.SDK.NET.Ref"가 자동으로 추가됩니다. 이후 일반적인 WinRT 응용 프로그램처럼 Windows 10 API를 가져다 쓸 수 있습니다.

일례로 "윈도우 데스크톱 응용 프로그램(예: Console)에서 알림 메시지(Toast notifications) 띄우기" 글에서 소개한 Toast 알림을 다룬 그 소스 코드 그대로 다음과 같이 복사해 쓸 수 있습니다.

using System;
using System.Windows.Forms;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ShowToast($"{nameof(WindowsFormsApp1)}", DateTime.Now.ToLongTimeString(), "Test Message", null);
        }

        static void ShowToast(string appId, string title, string message, string image)
        {
            XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(
                string.IsNullOrEmpty(image) ? ToastTemplateType.ToastText02 :
                ToastTemplateType.ToastImageAndText02);

            XmlNodeList stringElements = toastXml.GetElementsByTagName("text");
            stringElements[0].AppendChild(toastXml.CreateTextNode(title));
            stringElements[1].AppendChild(toastXml.CreateTextNode(message));

            if (string.IsNullOrEmpty(image) == false)
            {
                // Specify the absolute path to an image
                String imagePath = "file:///" + image;
                XmlNodeList imageElements = toastXml.GetElementsByTagName("image");
                imageElements[0].Attributes.GetNamedItem("src").NodeValue = imagePath;
            }

            ToastNotification toast = new ToastNotification(toastXml);

            toast.Activated += Toast_Activated;
            toast.Dismissed += Toast_Dismissed;
            toast.Failed += Toast_Failed;

            ToastNotificationManager.CreateToastNotifier(appId).Show(toast);
        }

        private static void Toast_Failed(ToastNotification sender, ToastFailedEventArgs args)
        {
        }

        private static void Toast_Dismissed(ToastNotification sender, ToastDismissedEventArgs args)
        {
        }

        private static void Toast_Activated(ToastNotification sender, object args)
        {
        }
    }
}

물론, 원문 글(Calling Windows APIs in .NET5")에서처럼 GPS 장치를 접근하는 것도 가능하고,

private async void button2_Click(object sender, EventArgs e)
{
    var locator = new Windows.Devices.Geolocation.Geolocator();
    var location = await locator.GetGeopositionAsync();
    var position = location.Coordinate.Point.Position;
    var latlong = string.Format("lat:{0}, long:{1}",
                                position.Latitude, position.Longitude);
    MessageBox.Show(latlong);
}

(원문에서는 WPF 프로젝트였지만) 카메라 접근으로 사진 찍는 기능도 다음과 같이 쉽게 구현할 수 있습니다.

private async void button3_Click(object sender, EventArgs e)
{
    // Initialize the webcam
    MediaCapture captureManager = new MediaCapture();
    await captureManager.InitializeAsync();

    ImageEncodingProperties imgFormat = ImageEncodingProperties.CreateJpeg();
    // create storage file in local app storage
    StorageFile file =
                await KnownFolders.CameraRoll.CreateFileAsync("TestPhoto.jpg",
                                    CreationCollisionOption.GenerateUniqueName);

    // take photo
    await captureManager.CapturePhotoToStorageFileAsync(imgFormat, file);

    Bitmap bitmap = new Bitmap(file.Path);
    pictureBox1.Image = bitmap;
}

net5_winrt_sample_1.png

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




암튼, 간단해져서 좋습니다. ^^ 기존에는 System.Runtime.WindowsRuntime.dll이나 Windows.winmd 파일 등을 신경써야 했는데 이제는 단순히 적절한 TFM만 지정하는 것으로 모든 준비 작업이 끝납니다.

참고로, 하나의 프로젝트 파일로 .NET Core 3.1과 .NET 5 지원을 모두 추가할 수 있습니다. 이를 위해 프로젝트 파일만 다음과 같이 살짝 바꾸면 됩니다.

<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFrameworks>netcoreapp3.1;net5.0-windows10.0.19041.0</TargetFrameworks>
    <UseWPF>true</UseWPF>
  </PropertyGroup>
  <ItemGroup>
   <PackageReference Condition="'$(TargetFramework)' == 'netcoreapp3.1'"
                     Include="Microsoft.Windows.SDK.Contracts"
                     Version="10.0.19041.0" />
  </ItemGroup>
</Project>




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 3/8/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2020-12-31 08시58분
[dimohy] 우리나라 윈도우 사용자가 모두 윈도우10으로 빨리빨리 넘어갔으면 합니다. ^^b
[guest]

1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13375정성태6/20/20232991스크립트: 50. Transformers (신경망 언어모델 라이브러리) 강좌 - 2장 코드 실행 결과
13374정성태6/20/20233122오류 유형: 866. 파이썬 - <class 'AttributeError'> module 'flask.json' has no attribute 'JSONEncoder'
13373정성태6/19/20234416오류 유형: 865. 파이썬 - pymssql 설치 관련 오류 정리
13372정성태6/15/20233129개발 환경 구성: 682. SQL Server TLS 통신을 위해 사용되는 키 길이 확인 방법
13371정성태6/15/20233150개발 환경 구성: 681. openssl - 인증서 버전(V1 / V3)
13370정성태6/14/20233316개발 환경 구성: 680. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 - TLS 1.2 지원
13369정성태6/13/20233116개발 환경 구성: 679. PyCharm(을 비롯해 JetBrains에 속한 여타) IDE에서 내부 Window들의 탭이 없어진 경우
13368정성태6/13/20233246개발 환경 구성: 678. openssl로 생성한 인증서를 SQL Server의 암호화 인증서로 설정하는 방법
13367정성태6/10/20233353오류 유형: 864. openssl로 만든 pfx 인증서를 Windows Server 2016 이하에서 등록 시 "The password you entered is incorrect" 오류 발생
13366정성태6/10/20233144.NET Framework: 2128. C# - 윈도우 시스템에서 지원하는 암호화 목록(Cipher Suites) 나열파일 다운로드1
13365정성태6/8/20232913오류 유형: 863. MODIFY FILE encountered operating system error 112(failed to retrieve text for this error. Reason: 15105)
13364정성태6/8/20233700.NET Framework: 2127. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 [1]
13363정성태6/7/20233266스크립트: 49. 파이썬 - "Transformers (신경망 언어모델 라이브러리) 강좌" - 1장 2절 코드 실행 결과
13362정성태6/1/20233178.NET Framework: 2126. C# - 서버 측의 요청 제어 (Microsoft.AspNetCore.RateLimiting)파일 다운로드1
13361정성태5/31/20233641오류 유형: 862. Facebook - ASP.NET/WebClient 사용 시 graph.facebook.com/me 호출에 대해 403 Forbidden 오류
13360정성태5/31/20233037오류 유형: 861. WSL/docker - failed to start shim: start failed: io.containerd.runc.v2: create new shim socket
13359정성태5/19/20233356오류 유형: 860. Docker Desktop - k8s 초기화 무한 반복한다면?
13358정성태5/17/20233667.NET Framework: 2125. C# - Semantic Kernel의 Semantic Memory 사용 예제 [1]파일 다운로드1
13357정성태5/16/20233468.NET Framework: 2124. C# - Semantic Kernel의 Planner 사용 예제파일 다운로드1
13356정성태5/15/20233777DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
13355정성태5/12/20233711.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현 [1]파일 다운로드1
13354정성태5/12/20233975.NET Framework: 2122. C# - "Use Unicode UTF-8 for worldwide language support" 설정을 한 경우, 한글 입력이 '\0' 문자로 처리
13352정성태5/12/20233592.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지파일 다운로드1
13351정성태5/11/20234095VS.NET IDE: 185. Visual Studio - 원격 Docker container 내에 실행 중인 응용 프로그램에 대한 디버깅 [1]
13350정성태5/11/20233346오류 유형: 859. Windows Date and Time - Unable to continue. You do not have permission to perform this task
13349정성태5/11/20233685.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제파일 다운로드1
1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...