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)
13483정성태12/14/20232315닷넷: 2184. C# - 하나의 resource 파일을 여러 프로그램에서 (AOT 시에도) 사용하는 방법파일 다운로드1
13482정성태12/13/20232908닷넷: 2183. C# - eFriend Expert OCX 예제를 .NET Core/5+ Console App에서 사용하는 방법 [2]파일 다운로드1
13481정성태12/13/20232287개발 환경 구성: 693. msbuild - .NET Core/5+ 프로젝트에서 resgen을 이용한 리소스 파일 생성 방법파일 다운로드1
13480정성태12/12/20232660개발 환경 구성: 692. Windows WSL 2 + Chrome 웹 브라우저 설치
13479정성태12/11/20232340개발 환경 구성: 691. WSL 2 (Ubuntu) + nginx 환경 설정
13477정성태12/8/20232532닷넷: 2182. C# - .NET 7부터 추가된 Int128, UInt128 [1]파일 다운로드1
13476정성태12/8/20232269닷넷: 2181. C# - .NET 8 JsonStringEnumConverter의 AOT를 위한 개선파일 다운로드1
13475정성태12/7/20232335닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회파일 다운로드1
13474정성태12/6/20232181개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
13473정성태12/5/20232391닷넷: 2179. C# - 값 형식(Blittable)을 메모리 복사를 이용해 바이트 배열로 직렬화/역직렬화파일 다운로드1
13472정성태12/4/20232198C/C++: 164. Visual C++ - InterlockedCompareExchange128 사용 방법
13471정성태12/4/20232277Copilot - To enable GitHub Copilot, authorize this extension using GitHub's device flow
13470정성태12/2/20232571닷넷: 2178. C# - .NET 8부터 COM Interop에 대한 자동 소스 코드 생성 도입파일 다운로드1
13469정성태12/1/20232297닷넷: 2177. C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법파일 다운로드1
13468정성태12/1/20232232닷넷: 2176. C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식파일 다운로드1
13467정성태11/30/20232330오류 유형: 882. C# - Unhandled exception. System.Runtime.InteropServices.COMException (0x800080A5)파일 다운로드1
13466정성태11/29/20232499닷넷: 2175. C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션
13465정성태11/28/20232246개발 환경 구성: 689. MSBuild - CopyToOutputDirectory가 "dotnet publish" 시에는 적용되지 않는 문제파일 다운로드1
13464정성태11/28/20232390닷넷: 2174. C# - .NET 7부터 UnmanagedCallersOnly 함수 export 기능을 AOT 빌드에 통합파일 다운로드1
13463정성태11/27/20232302오류 유형: 881. Visual Studio - NU1605: Warning As Error: Detected package downgrade
13462정성태11/27/20232344오류 유형: 880. Visual Studio - error CS0246: The type or namespace name '...' could not be found
13461정성태11/26/20232380닷넷: 2173. .NET Core 3/5+ 기반의 COM Server를 registry 등록 없이 사용하는 방법파일 다운로드1
13460정성태11/26/20232333닷넷: 2172. .NET 6+ 기반의 COM Server 내에 Type Library를 내장하는 방법파일 다운로드1
13459정성태11/26/20232314닷넷: 2171. .NET Core 3/5+ 기반의 COM Server를 기존의 regasm처럼 등록하는 방법파일 다운로드1
13458정성태11/26/20232335닷넷: 2170. .NET Core/5+ 기반의 COM Server를 tlb 파일을 생성하는 방법(tlbexp)
13457정성태11/25/20232275VS.NET IDE: 187. Visual Studio - 16.9 버전부터 추가된 "Display inline type hints" 옵션
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...