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




윈도우 데스크톱 응용 프로그램(예: Console)에서 알림 메시지(Toast notifications) 띄우기

이 글은 다음의 내용을 실습한 글입니다.

How to send Windows Toast notifications from Console apps 
; http://blog.plasticscm.com/2016/08/how-to-send-windows-toast-notifications.html




자, 그럼 간단하게 Console Application으로 시작해보겠습니다.

결국 데스크톱 응용 프로그램에서 UWP의 Toast 알림을 사용하는 것은 UWP 라이브러리를 참조하는 것으로 해결할 수 있습니다. 그리고 이를 위해서는 약간의 사전 작업이 필요한데, 이에 대해서는 전에 다음의 글을 통해 설명한 적이 있습니다.

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

즉, StoreApp/UWP 환경은 윈도우 8부터 제공되는 것이기 때문에 UWP 라이브러리를 사용하려면 우선 여러분들의 응용 프로그램을 Windows 8 이후의 버전만 지원한다는 표시를 해야 합니다. 이를 위해 csproj 파일을 열어 TargetPlatformVersion을 지정합니다.

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" ...[생략]...>
  <Import ...[생략]... />
  <PropertyGroup>
    <TargetPlatformVersion>8.0</TargetPlatformVersion>
  </PropertyGroup>
    ...[생략]...
</Project>

그다음, 관련 UWP 라이브러리만 추가해주면 됩니다. ^^ (아래의 경로는 개발자마다 다를 수 있습니다.)

C:\Program Files (x86)\Windows Kits\8.1\References\CommonConfiguration\Neutral\Windows.winmd
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\WindowsBase.dll
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\Facades\System.Runtime.dll

이후, UWP에서와 동일하게 Toast 알림 메시지를 띄우는 코드를 작성하면 됩니다.

static void Main(string[] args)
{
    Console.WriteLine("Type 'exit' to quit. ENTER to show a notification");

    while (true)
    {
        string txt = Console.ReadLine();
        if (txt == "exit")
        {
            break;
        }

        ShowToast("ConsoleToast.App", DateTime.Now.ToLongTimeString(), "this is a message: " + txt, 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)
{
}

그런데, 여기서 한 가지 문제가 있습니다. 문서에 보면 데스크톱 응용 프로그램의 경우 Toast 알림을 보내려면 다음과 같은 부가적인 절차가 필요하다고 합니다.

  • For a desktop app to display a toast, the app must have a shortcut on the Start screen.
  • The shortcut must have an AppUserModelID.
  • Desktop apps cannot schedule a toast.

관련 코딩 작업이 함께 제공되는데,

How to enable desktop toast notifications through an AppUserModelID
; https://docs.microsoft.com/en-us/previous-versions/windows/desktop/legacy/hh802762(v=vs.85)

Sending toast notifications from desktop apps sample
; https://code.msdn.microsoft.com/windowsdesktop/sending-toast-notifications-71e230a2/

그냥 베껴서 써도 됩니다. ^^

static class ShortCutCreator
{
    // In order to display toasts, a desktop application must have
    // a shortcut on the Start menu.
    // Also, an AppUserModelID must be set on that shortcut.
    // The shortcut should be created as part of the installer.
    // The following code shows how to create
    // a shortcut and assign an AppUserModelID using Windows APIs.
    // You must download and include the Windows API Code Pack
    // for Microsoft .NET Framework for this code to function

    internal static bool TryCreateShortcut(string appId, string appName)
    {
        String shortcutPath = Environment.GetFolderPath(
            Environment.SpecialFolder.ApplicationData) +
            "\\Microsoft\\Windows\\Start Menu\\Programs\\" + appName + ".lnk";
        if (!File.Exists(shortcutPath))
        {
            InstallShortcut(appId, shortcutPath);
            return true;
        }
        return false;
    }

    static void InstallShortcut(string appId, string shortcutPath)
    {
        // Find the path to the current executable
        String exePath = Process.GetCurrentProcess().MainModule.FileName;
        IShellLinkW newShortcut = (IShellLinkW)new CShellLink();

        // Create a shortcut to the exe
        VerifySucceeded(newShortcut.SetPath(exePath));
        VerifySucceeded(newShortcut.SetArguments(""));

        // Open the shortcut property store, set the AppUserModelId property
        IPropertyStore newShortcutProperties = (IPropertyStore)newShortcut;

        using (PropVariant applicationId = new PropVariant(appId))
        {
            VerifySucceeded(newShortcutProperties.SetValue(
                SystemProperties.System.AppUserModel.ID, applicationId));
            VerifySucceeded(newShortcutProperties.Commit());
        }

        // Commit the shortcut to disk
        IPersistFile newShortcutSave = (IPersistFile)newShortcut;

        VerifySucceeded(newShortcutSave.Save(shortcutPath, true));
    }

    static void VerifySucceeded(UInt32 hresult)
    {
        if (hresult <= 1)
            return;

        throw new Exception("Failed with HRESULT: " + hresult.ToString("X"));
    }
}

단지, 위의 소스 코드에서 사용된 PropVariant같은 타입이 Microsoft.WindowsAPICodePack에 포함되어 있어서 이에 대한 라이브러리를 NuGet을 통해 추가해야 합니다.

PM> Install-Package Microsoft.WindowsAPICodePack.Core 
PM> Install-Package Microsoft.WindowsAPICodePack.Shell 

이것으로 준비는 모두 끝입니다. 그냥 우리들의 응용 프로그램 또는 그것의 설치 파일에서 다음과 같은 메서드를 한 번만 호출해 주면 됩니다.

ShortCutCreator.TryCreateShortcut("ConsoleToast.App", "ConsoleToast");

위의 코드가 불리면 다음과 같은 경로에 .lnk 단축 아이콘이 생성됩니다.

%USERPROFILE%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs

이제 실행시키면 Windows 8 / 10에서 Toast 알림 메시지가 정상적으로 나오는 것을 확인할 수 있습니다.

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




재미있는 점이 있다면, Windows 8에서는 AppModel과 연결된 .lnk 단축 아이콘이 반드시 생성되어야 했지만, Windows 10부터는 이런 제약이 사라진 것 같습니다. 실제로 테스트해보면 10에서는 ShortCutCreator.TryCreateShortcut 메서드를 호출하지 않은 상태에서도 Toast 알림이 잘 생성되었습니다. (단지, 최초 응용 프로그램을 실행 후 첫 번째 알림은 나타나지 않았습니다.)

다음은 "%USERPROFILE%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs" 경로에 단축 아이콘 등록 없이 Toast 알림을 생성한 것을 보여줍니다.

toast_notif_1.png




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







[최초 등록일: ]
[최종 수정일: 7/17/2021]

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

비밀번호

댓글 작성자
 



2023-05-08 06시39분
Day 150 : Laptop Notification with Python
; https://www.youtube.com/watch?v=JY-2rDuQI7I
정성태

... 46  47  48  49  50  51  52  53  54  55  56  57  58  59  [60]  ...
NoWriterDateCnt.TitleFile(s)
12126정성태1/25/202010732.NET Framework: 880. C# - PE 파일로부터 IMAGE_COR20_HEADER 및 VTableFixups 테이블 분석파일 다운로드1
12125정성태1/24/20208601VS.NET IDE: 141. IDE0019 - Use pattern matching
12124정성태1/23/202010435VS.NET IDE: 140. IDE1006 - Naming rule violation: These words must begin with upper case characters: ...
12123정성태1/23/202011912웹: 39. Google Analytics - gtag 함수를 이용해 페이지 URL 수정 및 별도의 이벤트 생성 방법 [2]
12122정성태1/20/20208892.NET Framework: 879. C/C++의 UNREFERENCED_PARAMETER 매크로를 C#에서 우회하는 방법(IDE0060 - Remove unused parameter '...')파일 다운로드1
12121정성태1/20/20209426VS.NET IDE: 139. Visual Studio - Error List: "Could not find schema information for the ..."파일 다운로드1
12120정성태1/19/202010877.NET Framework: 878. C# DLL에서 Win32 C/C++처럼 dllexport 함수를 제공하는 방법 - 네 번째 이야기(IL 코드로 직접 구현)파일 다운로드1
12119정성태1/17/202010909디버깅 기술: 160. Windbg 확장 DLL 만들기 (3) - C#으로 만드는 방법
12118정성태1/17/202011539개발 환경 구성: 466. C# DLL에서 Win32 C/C++처럼 dllexport 함수를 제공하는 방법 - 세 번째 이야기 [1]
12117정성태1/15/202010565디버깅 기술: 159. C# - 디버깅 중인 프로세스를 강제로 다른 디버거에서 연결하는 방법파일 다운로드1
12116정성태1/15/202011047디버깅 기술: 158. Visual Studio로 디버깅 시 sos.dll 확장 명령어를 (비롯한 windbg의 다양한 기능을) 수행하는 방법
12115정성태1/14/202010832디버깅 기술: 157. C# - PEB.ProcessHeap을 이용해 디버깅 중인지 확인하는 방법파일 다운로드1
12114정성태1/13/202012687디버깅 기술: 156. C# - PDB 파일로부터 심벌(Symbol) 및 타입(Type) 정보 열거 [1]파일 다운로드3
12113정성태1/12/202013304오류 유형: 590. Visual C++ 빌드 오류 - fatal error LNK1104: cannot open file 'atls.lib' [1]
12112정성태1/12/20209911오류 유형: 589. PowerShell - 원격 Invoke-Command 실행 시 "WinRM cannot complete the operation" 오류 발생
12111정성태1/12/202013107디버깅 기술: 155. C# - KernelMemoryIO 드라이버를 이용해 실행 프로그램을 숨기는 방법(DKOM: Direct Kernel Object Modification) [16]파일 다운로드1
12110정성태1/11/202011700디버깅 기술: 154. Patch Guard로 인해 블루 스크린(BSOD)가 발생하는 사례 [5]파일 다운로드1
12109정성태1/10/20209629오류 유형: 588. Driver 프로젝트 빌드 오류 - Inf2Cat error -2: "Inf2Cat, signability test failed."
12108정성태1/10/20209677오류 유형: 587. Kernel Driver 시작 시 127(The specified procedure could not be found.) 오류 메시지 발생
12107정성태1/10/202010653.NET Framework: 877. C# - 프로세스의 모든 핸들을 열람 - 두 번째 이야기
12106정성태1/8/202012029VC++: 136. C++ - OSR Driver Loader와 같은 Legacy 커널 드라이버 설치 프로그램 제작 [1]
12105정성태1/8/202010702디버깅 기술: 153. C# - PEB를 조작해 로드된 DLL을 숨기는 방법
12104정성태1/7/202011426DDK: 9. 커널 메모리를 읽고 쓰는 NT Legacy driver와 C# 클라이언트 프로그램 [4]
12103정성태1/7/202014095DDK: 8. Visual Studio 2019 + WDK Legacy Driver 제작- Hello World 예제 [1]파일 다운로드2
12102정성태1/6/202011751디버깅 기술: 152. User 권한(Ring 3)의 프로그램에서 _ETHREAD 주소(및 커널 메모리를 읽을 수 있다면 _EPROCESS 주소) 구하는 방법
12101정성태1/5/202011106.NET Framework: 876. C# - PEB(Process Environment Block)를 통해 로드된 모듈 목록 열람
... 46  47  48  49  50  51  52  53  54  55  56  57  58  59  [60]  ...