Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (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




C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어

비록 UWP는 수명을 다했지만, Win32의 후속으로 나온 WinRT는 (WinUI 3 프로젝트에서도 사용하게 되면서) 살아남고 있는데요, 간혹 Raymond Chen의 블로그를 보면 심심치 않게 WinRT를, 그것도 C++/WinRT 응용 프로그램을 만드는 것을 볼 수 있습니다.

이번 글도 마찬가지인데요,

How can I get information about media playing on the system, and optionally control their playback?
; https://devblogs.microsoft.com/oldnewthing/20231108-00/?p=108980

친절하게도 (C++와 함께) C# 소스 코드까지 실어 소개하고 있습니다.

using Windows.ApplicationModel;
using Windows.Media.Control;

class Program
{
    static string DisplayNameFromAppId(string appid)
    {
        try
        {
            return AppInfo.GetFromAppUserModelId(appid).DisplayInfo.DisplayName;
        }
        catch (Exception)
        {
            return appid;
        }
    }


    static async Task Run()
    {
        var manager =
            await GlobalSystemMediaTransportControlsSessionManager.RequestAsync();
        var current = manager.GetCurrentSession();
        if (current != null)
        {
            Console.WriteLine("Current media app: " +
                              DisplayNameFromAppId(current.SourceAppUserModelId));
        }
        foreach (var session in manager.GetSessions())
        {
            Console.WriteLine("Session from: " +
                              DisplayNameFromAppId(session.SourceAppUserModelId));

            var timelineProperties = session.GetTimelineProperties();
            Console.WriteLine($"\tPosition: {timelineProperties.Position}");
            Console.WriteLine($"\tStart: {timelineProperties.StartTime}");
            Console.WriteLine($"\tEnd: {timelineProperties.EndTime}");

            var info = session.GetPlaybackInfo();
            var rate = info.PlaybackRate;
            if (rate != null)
            {
                Console.WriteLine($"\tPlayback speed: {rate.Value}");
            }

            var controls = info.Controls;
            Console.WriteLine($"\tCan pause: {controls.IsPauseEnabled}");

            if (info.PlaybackStatus ==
                GlobalSystemMediaTransportControlsSessionPlaybackStatus.Playing &&
                controls.IsPauseEnabled)
            {
                await session.TryPauseAsync();
            }
        }
    }

    [MTAThread]
    public static void Main()
    {
        Run().Wait();
    }
}

사용법이 매우 단순한데요, GlobalSystemMediaTransportControlsSessionManager를 구한 후 Session을 열거하는 것으로, 현재 시스템에 실행 중인 다양한 Media 재생기를 제어하고 있습니다.

실제로, 제 컴퓨터에서 윈도우에 기본 포함된 "Media Player"로 mp3 음악을 재생하면서 동시에 Edge 브라우저를 실행해 유튜브 영상을 틀은 상태로 저 코드를 실행했더니 다음과 같은 출력 결과가 나오고,

Current media app: Media Player
Session from: Media Player
        Position: 00:00:47.3734145
        Start: 00:00:00
        End: 00:05:28.1916666
        Playback speed: 1
        Can pause: True
Session from: MSEdge
        Position: 00:00:00.0424370
        Start: 00:00:00
        End: 00:01:59.4210000
        Playback speed: 1
        Can pause: True

"await session.TryPauseAsync();" 코드의 수행에 따라 재생하는 것을 모두 멈췄습니다.

아마도, 저 과정을 단순히 Win32 API를 이용해 만들어야 한다면 꽤 복잡했을 텐데, 그런 의미에서 본다면 (닷넷을 포함한) 윈도우 개발자에게 있어 WinRT는 이제 꽤나 쓸만한, 사용해도 좋을 API 셋이 되었습니다.




참고로, 위의 코드를 .NET 7 콘솔 프로젝트에서 수행하려면 프로젝트에서 TargetFramework 값을 다음과 같이 바꿔야 합니다.

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

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0-windows10.0.19041.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>

"net7.0-windows" 이후에 붙는 버전은 다양할 수 있지만, Windows 10의 경우에는 반드시 최소 19041 이상으로 설정해야 합니다. 만약, 18362 이하로 설정하면 이런 에러가 납니다.

error CS0117: 'AppInfo' does not contain a definition for 'GetFromAppUserModelId'

그나저나, TargetFramework의 버전으로 가용한 값은 어떻게 구할 수 있을까요? 여러 문서를 뒤져봤지만,

Call Windows Runtime APIs in desktop apps
; https://learn.microsoft.com/en-us/windows/apps/desktop/modernize/desktop-to-uwp-enhance

Windows SDK and emulator archive
; https://developer.microsoft.com/en-us/windows/downloads/sdk-archive/

가장 확실한 방법은 그냥 아무 숫자나 넣어보고 오류를 내는 것이었습니다. ^^; 그런 경우 다음과 같이 컴파일 오류가 나면서 허용하는 버전 목록을 보여주기 때문입니다.

// 2023년 11월 9일 기준이며, 향후에는 결과가 달라질 수 있습니다.

1>C:\Program Files\dotnet\sdk\7.0.403\...[생략]...: error NETSDK1140: 5555.0.0.0 is not a valid TargetPlatformVersion for Windows. Valid versions include:
1>C:\Program Files\dotnet\sdk\7.0.403\...[생략]...: error NETSDK1140: 10.0.22621.0
1>C:\Program Files\dotnet\sdk\7.0.403\...[생략]...: error NETSDK1140: 10.0.22000.0
1>C:\Program Files\dotnet\sdk\7.0.403\...[생략]...: error NETSDK1140: 10.0.20348.0
1>C:\Program Files\dotnet\sdk\7.0.403\...[생략]...: error NETSDK1140: 10.0.19041.0
1>C:\Program Files\dotnet\sdk\7.0.403\...[생략]...: error NETSDK1140: 10.0.18362.0
1>C:\Program Files\dotnet\sdk\7.0.403\...[생략]...: error NETSDK1140: 10.0.17763.0
1>C:\Program Files\dotnet\sdk\7.0.403\...[생략]...: error NETSDK1140: 8.0
1>C:\Program Files\dotnet\sdk\7.0.403\...[생략]...: error NETSDK1140: 7.0

출력 결과에서 약간 혼란스러운 것은 Windows 11을 대상으로 하는 경우에도 Major 버전 번호가 10이라는 점입니다. 문서에 보면, 22000 버전 이상은 Windows 11이라고 하고, 그 미만은 Windows 10입니다.

예상했겠지만, 저 버전들은 Windows 10/11의 릴리스/패치 번호에 해당하는데요,

Windows 11 release information
; https://learn.microsoft.com/en-us/windows/release-health/windows11-release-information

Windows 10 release information
; https://learn.microsoft.com/en-us/windows/release-health/release-information

따라서, TargetFramework은 현재 응용 프로그램에서 사용하는 API를 만족시키면서도 가능한 낮은 버전으로 지정하는 것이 좋습니다.




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







[최초 등록일: ]
[최종 수정일: 11/9/2023]

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

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  10  11  12  [13]  14  15  ...
NoWriterDateCnt.TitleFile(s)
13316정성태4/10/20233644오류 유형: 854. docker-compose 시 "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)" 오류 발생
13315정성태4/10/20233911Windows: 245. Win32 - 시간 만료를 갖는 컨텍스트 메뉴와 윈도우 메시지의 영역별 정의파일 다운로드1
13314정성태4/9/20234063개발 환경 구성: 672. DosBox를 이용한 Turbo C, Windows 3.1 설치
13313정성태4/9/20234078개발 환경 구성: 671. Hyper-V VM에 Turbo C 2.0 설치 [2]
13312정성태4/8/20234159Windows: 244. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (개선된 버전)파일 다운로드1
13311정성태4/7/20234602C/C++: 163. Visual Studio 2022 - DirectShow 예제 컴파일(WAV Dest)
13310정성태4/6/20234256C/C++: 162. Visual Studio - /NODEFAULTLIB 옵션 설정 후 수동으로 추가해야 할 library
13309정성태4/5/20234384.NET Framework: 2107. .NET 6+ FileStream의 구조 변화
13308정성태4/4/20234271스크립트: 47. 파이썬의 time.time() 실숫값을 GoLang / C#에서 사용하는 방법
13307정성태4/4/20234049.NET Framework: 2106. C# - .NET Core/5+ 환경의 Windows Forms 응용 프로그램에서 HINSTANCE 구하는 방법
13306정성태4/3/20233909Windows: 243. Win32 - 윈도우(cbWndExtra) 및 윈도우 클래스(cbClsExtra) 저장소 사용 방법
13305정성태4/1/20234295Windows: 242. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (쉬운 버전)파일 다운로드1
13304정성태3/31/20234601VS.NET IDE: 181. Visual Studio - C/C++ 프로젝트에 application manifest 적용하는 방법
13303정성태3/30/20233934Windows: 241. 환경 변수 %PATH%에 DLL을 찾는 규칙
13302정성태3/30/20234552Windows: 240. RDP 환경에서 바뀌는 %TEMP% 디렉터리 경로
13301정성태3/29/20234650Windows: 239. C/C++ - Windows 10 Version 1607부터 지원하는 /DEPENDENTLOADFLAG 옵션파일 다운로드1
13300정성태3/28/20234350Windows: 238. Win32 - Modal UI 창에 올바른 Owner(HWND)를 설정해야 하는 이유
13299정성태3/27/20234096Windows: 237. Win32 - 모든 메시지 루프를 탈출하는 WM_QUIT 메시지
13298정성태3/27/20234068Windows: 236. Win32 - MessageBeep 소리가 안 들린다면?
13297정성태3/26/20234690Windows: 235. Win32 - Code Modal과 UI Modal
13296정성태3/25/20234058Windows: 234. IsDialogMessage와 협업하는 WM_GETDLGCODE Win32 메시지 [1]파일 다운로드1
13295정성태3/24/20234296Windows: 233. Win32 - modeless 대화창을 modal처럼 동작하게 만드는 방법파일 다운로드1
13294정성태3/22/20234465.NET Framework: 2105. LargeAddressAware 옵션이 적용된 닷넷 32비트 프로세스의 가용 메모리 - 두 번째
13293정성태3/22/20234517오류 유형: 853. dumpbin - warning LNK4048: Invalid format file; ignored
13292정성태3/21/20234668Windows: 232. C/C++ - 일반 창에도 사용 가능한 IsDialogMessage파일 다운로드1
13291정성태3/20/20235009.NET Framework: 2104. C# Windows Forms - WndProc 재정의와 IMessageFilter 사용 시의 차이점
1  2  3  4  5  6  7  8  9  10  11  12  [13]  14  15  ...