Microsoft MVP성태의 닷넷 이야기
.NET Framework: 991. .NET 5 응용 프로그램에서 WinRT API 호출 [링크 복사], [링크+제목 복사]
조회: 10044
글쓴 사람
정성태 (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]

... 16  17  18  19  20  21  22  23  24  25  26  27  28  29  [30]  ...
NoWriterDateCnt.TitleFile(s)
12871정성태12/12/20217460오류 유형: 771. docker: Error response from daemon: OCI runtime create failed
12870정성태12/9/20216066개발 환경 구성: 614. 파이썬 - PyPI 패키지 만들기 (4) package_data 옵션
12869정성태12/8/20218270개발 환경 구성: 613. git clone 실행 시 fingerprint 묻는 단계를 생략하는 방법
12868정성태12/7/20216840오류 유형: 770. twine 업로드 시 "HTTPError: 400 Bad Request ..." 오류 [1]
12867정성태12/7/20216547개발 환경 구성: 612. 파이썬 - PyPI 패키지 만들기 (3) entry_points 옵션
12866정성태12/7/202113919오류 유형: 769. "docker build ..." 시 "failed to solve with frontend dockerfile.v0: failed to read dockerfile ..." 오류
12865정성태12/6/20216614개발 환경 구성: 611. 파이썬 - PyPI 패키지 만들기 (2) long_description, cmdclass 옵션
12864정성태12/6/20215088Linux: 46. WSL 환경에서 find 명령을 사용해 파일을 찾는 방법
12863정성태12/4/20216987개발 환경 구성: 610. 파이썬 - PyPI 패키지 만들기
12862정성태12/3/20215728오류 유형: 768. Golang - 빌드 시 "cmd/go: unsupported GOOS/GOARCH pair linux /amd64" 오류
12861정성태12/3/20217951개발 환경 구성: 609. 파이썬 - "Windows embeddable package"로 개발 환경 구성하는 방법
12860정성태12/1/20216056오류 유형: 767. SQL Server - 127.0.0.1로 접속하는 경우 "Access is denied"가 발생한다면?
12859정성태12/1/202112207개발 환경 구성: 608. Hyper-V 가상 머신에 Console 모드로 로그인하는 방법
12858정성태11/30/20219463개발 환경 구성: 607. 로컬의 USB 장치를 원격 머신에 제공하는 방법 - usbip-win
12857정성태11/24/20216959개발 환경 구성: 606. WSL Ubuntu 20.04에서 파이썬을 위한 uwsgi 설치 방법
12856정성태11/23/20218742.NET Framework: 1121. C# - 동일한 IP:Port로 바인딩 가능한 서버 소켓 [2]
12855정성태11/13/20216138개발 환경 구성: 605. Azure App Service - Kudu SSH 환경에서 FTP를 이용한 파일 전송
12854정성태11/13/20217676개발 환경 구성: 604. Azure - 윈도우 VM에서 FTP 여는 방법
12853정성태11/10/20216059오류 유형: 766. Azure App Service - JBoss 호스팅 생성 시 "This region has quota of 0 PremiumV3 instances for your subscription. Try selecting different region or SKU."
12851정성태11/1/20217369스크립트: 34. 파이썬 - MySQLdb 기본 예제 코드
12850정성태10/27/20218520오류 유형: 765. 우분투에서 pip install mysqlclient 실행 시 "OSError: mysql_config not found" 오류
12849정성태10/17/20217689스크립트: 33. JavaScript와 C#의 시간 변환 [1]
12848정성태10/17/20218646스크립트: 32. 파이썬 - sqlite3 기본 예제 코드 [1]
12847정성태10/14/20218485스크립트: 31. 파이썬 gunicorn - WORKER TIMEOUT 오류 발생
12846정성태10/7/20218256스크립트: 30. 파이썬 __debug__ 플래그 변수에 따른 코드 실행 제어
12845정성태10/6/20218097.NET Framework: 1120. C# - BufferBlock<T> 사용 예제 [5]파일 다운로드1
... 16  17  18  19  20  21  22  23  24  25  26  27  28  29  [30]  ...