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)
13417정성태9/19/20233632닷넷: 2145. C# - 제네릭의 형식 매개변수에 속한 (매개변수를 가진) 생성자를 호출하는 방법
13416정성태9/19/20233362오류 유형: 877. redis-py - MISCONF Redis is configured to save RDB snapshots, ...
13415정성태9/18/20233855닷넷: 2144. C# 12 - 컬렉션 식(Collection Expressions)
13414정성태9/16/20233672디버깅 기술: 193. Windbg - ThreadStatic 필드 값을 조사하는 방법
13413정성태9/14/20233873닷넷: 2143. C# - 시스템 Time Zone 변경 시 이벤트 알림을 받는 방법
13412정성태9/14/20237196닷넷: 2142. C# 12 - 인라인 배열(Inline Arrays) [1]
13411정성태9/12/20233663Windows: 252. 권한 상승 전/후 따로 관리되는 공유 네트워크 드라이브 정보
13410정성태9/11/20235238닷넷: 2141. C# 12 - Interceptor (컴파일 시에 메서드 호출 재작성) [1]
13409정성태9/8/20234050닷넷: 2140. C# - Win32 API를 이용한 모니터 전원 끄기
13408정성태9/5/20234035Windows: 251. 임의로 만든 EXE 파일을 포함한 ZIP 파일의 압축을 해제할 때 Windows Defender에 의해 삭제되는 경우
13407정성태9/4/20233714닷넷: 2139. C# - ParallelEnumerable을 이용한 IEnumerable에 대한 병렬 처리
13406정성태9/4/20233747VS.NET IDE: 186. Visual Studio Community 버전의 라이선스
13405정성태9/3/20234108닷넷: 2138. C# - async 메서드 호출 원칙
13404정성태8/29/20233671오류 유형: 876. Windows - 키보드의 등호(=, Equals sign) 키가 눌리지 않는 경우
13403정성태8/21/20233487오류 유형: 875. The following signatures couldn't be verified because the public key is not available: NO_PUBKEY EB3E94ADBE1229CF
13402정성태8/20/20233589닷넷: 2137. ILSpy의 nuget 라이브러리 버전 - ICSharpCode.Decompiler
13401정성태8/19/20233842닷넷: 2136. .NET 5+ 환경에서 P/Invoke의 성능을 높이기 위한 SuppressGCTransition 특성 [1]
13400정성태8/10/20233701오류 유형: 874. 파이썬 - pymssql을 윈도우 환경에서 설치 불가
13399정성태8/9/20233560닷넷: 2135. C# - 지역 변수로 이해하는 메서드 매개변수의 값/참조 전달
13398정성태8/3/20234435스크립트: 55. 파이썬 - pyodbc를 이용한 SQL Server 연결 사용법
13397정성태7/23/20233930닷넷: 2134. C# - 문자열 연결 시 string.Create를 이용한 GC 할당 최소화
13396정성태7/22/20233715스크립트: 54. 파이썬 pystack 소개 - 메모리 덤프로부터 콜 스택 열거
13395정성태7/20/20233545개발 환경 구성: 685. 로컬에서 개발 중인 ASP.NET Core/5+ 웹 사이트에 대해 localhost 이외의 호스트 이름으로 접근하는 방법
13394정성태7/16/20233499오류 유형: 873. Oracle.ManagedDataAccess.Client - 쿼리 수행 시 System.InvalidOperationException
13393정성태7/16/20233733닷넷: 2133. C# - Oracle 데이터베이스의 Sleep 쿼리 실행하는 방법
13392정성태7/16/20233603오류 유형: 872. Oracle - ORA-01031: insufficient privileges
1  2  3  4  5  6  7  8  [9]  10  11  12  13  14  15  ...