5

是否可以使用Toast NotificationManager從控制檯應用程序發送Toast通知?是否可以從控制檯應用程序發送Toast通知?

我知道這是可以從Windows通用應用發送Toast通知:

var toast = new ToastNotification(doc); 
ToastNotificationManager.CreateToastNotifier().Show(toast); 

*文檔 - 存儲在XML字符串吐司

要我需要Windows.UI.Notifications使用ToastNotificaionManager我不能在控制檯應用程序項目中引用的庫。

我之前提到的庫實際上是由WinRT使用的。是否可以在Windows控制檯應用程序中使用WinRT API?

+0

控制檯應用程序沒有GUI,因此Toast沒有意義,不是嗎? – ManoDestra

+0

敬酒什麼?看起來你已經回答了你自己的問題。 –

+0

通知有很多應用程序,在這種情況下,我真的很需要它 –

回答

11

首先需要聲明的是你的程序將要使用的WinRT庫:
1.右鍵單擊您的yourProject,選擇卸載項目
2.右鍵單擊您的youProject(不可用),然後單擊編輯yourProject.csproj
3.添加一個新的屬性組:<targetplatformversion>8.0</targetplatformversion>
4.裝項目
5.添加referece 的Windows的Windows>核心
enter image description here

現在,您需要添加以下代碼:

using Windows.UI.Notifications; 

,你將能夠使用這個代碼來發送通知:

var toast = new ToastNotification(doc); 
ToastNotificationManager.CreateToastNotifier().Show(toast); 

參考:How to call WinRT APIs in Windows 8 from C# Desktop Applications - WinRT Diagram

+0

編輯後,我的控制檯應用程序不會啓動參考錯誤:無法加載文件或程序集'System.Runtime,Version = 4.0.20.0,Culture = neutral,PublicKeyToken = b03f5f7f11d50a3a' – Jamby

3

我Evaldas B的代碼我錯過了一個字符串,在這裏遇到了一些問題。 (在那裏說需要字符串這裏)

.CreateToastNotifier(<needed a string here>).Show(toast);

警告我有點新的C#,所以我的代碼可能sucks-但它確實工作很簡單,這就是比我更可以說對於大多數我找到的解決方案

另外我有一個時間讓XML文檔閱讀。我與System.xml(我認爲)和Windows.Data.Dom.Xml(也不完全確定)戰鬥。 最後,我決定讓它們成爲我的示例文件的硬編碼字符串,並使用switch語句在它們之間切換。 我發現有很多人在堆棧溢出中尋找我提出的解決方案。似乎烤箱通知系統與控制檯或後臺應用程序的使用將會非常有用,而使用Windows應用程序圍繞在烤麪包通知系統周圍的文檔都表明它需要與應用程序一起使用。該行動中心對NotificationTray/NotifyIcon路由的通知和通知非常有用。我還沒有在網絡上的其他地方找到完整的解決方案。這裏是示例代碼。

/* 
At first you need to declare that your program will be using winRT libraries: 
1. Right click on your yourProject, select Unload Project 
2. Right click on your youProject(unavailable) and click Edit yourProject.csproj 
3. Add a new property group:<TargetPlatformVersion>8.0</TargetPlatformVersion> 
4. Reload project 
5. Add referece Windows from Windows > Core 
*/ 
using System; 
using Windows.Data.Xml.Dom; 
using Windows.Storage; 
using Windows.Storage.Streams; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using Windows.UI.Notifications; 

namespace ConsoleApplication6 
{ 
    public class NewToastNotification 
    { 
     public NewToastNotification(string input, int type) 
     { 
      string NotificationTextThing = input; 
      string Toast = ""; 
      switch (type) 
      { 
       case 1: 
        { 
         //Basic Toast 
         Toast = "<toast><visual><binding template=\"ToastImageAndText01\"><text id = \"1\" >"; 
         Toast += NotificationTextThing; 
         Toast += "</text></binding></visual></toast>"; 
         break; 
        } 
       default: 
        { 
         Toast = "<toast><visual><binding template=\"ToastImageAndText01\"><text id = \"1\" >"; 
         Toast += "Default Text String"; 
         Toast += "</text></binding></visual></toast>"; 
         break; 
        } 
      } 
      XmlDocument tileXml = new XmlDocument(); 
      tileXml.LoadXml(Toast); 
      var toast = new ToastNotification(tileXml); 
      ToastNotificationManager.CreateToastNotifier("New Toast Thing").Show(toast); 
     } 
} 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      NewToastNotification Window = new NewToastNotification("Yes",1); 


     } 
    } 
} 
+0

有沒有人對此的答案?傳遞給CreateToastNotifier調用的應用程序ID應該是什麼?如何找到該應用程序ID?我嘗試了許多可能的變體,查看通用應用程序清單,但其中沒有一個可行。吐司顯示,所有權利,但是當我點擊通用應用程序內的按鈕沒有啓動。其實在我的情況下,通用應用程序是桌面橋接通用應用程序,WPF包裝到UWP容器中。 – Alex

0

1)要使用控制檯或桌面應用程序顯示Toast通知,您的應用程序必須在開始菜單上有一個快捷方式。

2)如果應用程序在Windows的開始菜單中具有快捷圖標(不是平鋪圖標),則您的應用程序必須具有AppId。 要爲您創建快捷方式,您的應用程序將創建一個名爲ShellHelpers.cs的新類並在其中粘貼此代碼。

using System; 
using System.Runtime.InteropServices; 
using System.Text; 
using Microsoft.WindowsAPICodePack.Shell.PropertySystem; 
using MS.WindowsAPICodePack.Internal; 

namespace DesktopToastsSample.ShellHelpers 
{ 
    internal enum STGM : long 
    { 
     STGM_READ = 0x00000000L, 
    STGM_WRITE = 0x00000001L, 
    STGM_READWRITE = 0x00000002L, 
    STGM_SHARE_DENY_NONE = 0x00000040L, 
    STGM_SHARE_DENY_READ = 0x00000030L, 
    STGM_SHARE_DENY_WRITE = 0x00000020L, 
    STGM_SHARE_EXCLUSIVE = 0x00000010L, 
    STGM_PRIORITY = 0x00040000L, 
    STGM_CREATE = 0x00001000L, 
    STGM_CONVERT = 0x00020000L, 
    STGM_FAILIFTHERE = 0x00000000L, 
    STGM_DIRECT = 0x00000000L, 
    STGM_TRANSACTED = 0x00010000L, 
    STGM_NOSCRATCH = 0x00100000L, 
    STGM_NOSNAPSHOT = 0x00200000L, 
    STGM_SIMPLE = 0x08000000L, 
    STGM_DIRECT_SWMR = 0x00400000L, 
    STGM_DELETEONRELEASE = 0x04000000L, 
} 

internal static class ShellIIDGuid 
{ 
    internal const string IShellLinkW = "000214F9-0000-0000-C000-000000000046"; 
    internal const string CShellLink = "00021401-0000-0000-C000-000000000046"; 
    internal const string IPersistFile = "0000010b-0000-0000-C000-000000000046"; 
    internal const string IPropertyStore = "886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99"; 
} 

[ComImport, 
Guid(ShellIIDGuid.IShellLinkW), 
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] 
internal interface IShellLinkW 
{ 
    UInt32 GetPath(
     [Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, 
     int cchMaxPath, 
     //ref _WIN32_FIND_DATAW pfd, 
     IntPtr pfd, 
     uint fFlags); 
    UInt32 GetIDList(out IntPtr ppidl); 
    UInt32 SetIDList(IntPtr pidl); 
    UInt32 GetDescription(
     [Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, 
     int cchMaxName); 
    UInt32 SetDescription(
     [MarshalAs(UnmanagedType.LPWStr)] string pszName); 
    UInt32 GetWorkingDirectory(
     [Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszDir, 
     int cchMaxPath 
     ); 
    UInt32 SetWorkingDirectory(
     [MarshalAs(UnmanagedType.LPWStr)] string pszDir); 
    UInt32 GetArguments(
     [Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszArgs, 
     int cchMaxPath); 
    UInt32 SetArguments(
     [MarshalAs(UnmanagedType.LPWStr)] string pszArgs); 
    UInt32 GetHotKey(out short wHotKey); 
    UInt32 SetHotKey(short wHotKey); 
    UInt32 GetShowCmd(out uint iShowCmd); 
    UInt32 SetShowCmd(uint iShowCmd); 
    UInt32 GetIconLocation(
     [Out(), MarshalAs(UnmanagedType.LPWStr)] out StringBuilder pszIconPath, 
     int cchIconPath, 
     out int iIcon); 
    UInt32 SetIconLocation(
     [MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, 
     int iIcon); 
    UInt32 SetRelativePath(
     [MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, 
     uint dwReserved); 
    UInt32 Resolve(IntPtr hwnd, uint fFlags); 
    UInt32 SetPath(
     [MarshalAs(UnmanagedType.LPWStr)] string pszFile); 
} 

[ComImport, 
Guid(ShellIIDGuid.IPersistFile), 
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] 
internal interface IPersistFile 
{ 
    UInt32 GetCurFile(
     [Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile 
    ); 
    UInt32 IsDirty(); 
    UInt32 Load(
     [MarshalAs(UnmanagedType.LPWStr)] string pszFileName, 
     [MarshalAs(UnmanagedType.U4)] STGM dwMode); 
    UInt32 Save(
     [MarshalAs(UnmanagedType.LPWStr)] string pszFileName, 
     bool fRemember); 
    UInt32 SaveCompleted(
     [MarshalAs(UnmanagedType.LPWStr)] string pszFileName); 
} 
[ComImport] 
[Guid(ShellIIDGuid.IPropertyStore)] 
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] 
interface IPropertyStore 
{ 
    UInt32 GetCount([Out] out uint propertyCount); 
    UInt32 GetAt([In] uint propertyIndex, out PropertyKey key); 
    UInt32 GetValue([In] ref PropertyKey key, [Out] PropVariant pv); 
    UInt32 SetValue([In] ref PropertyKey key, [In] PropVariant pv); 
    UInt32 Commit(); 
} 


[ComImport, 
Guid(ShellIIDGuid.CShellLink), 
ClassInterface(ClassInterfaceType.None)] 
internal class CShellLink { } 

public static class ErrorHelper 
{ 
    public static void VerifySucceeded(UInt32 hresult) 
    { 
     if (hresult > 1) 
     { 
      throw new Exception("Failed with HRESULT: " + hresult.ToString("X")); 
     } 
    } 
} 
} 

代碼創建一個快捷方式(此代碼可以被添加到您還將展示舉杯同一個類)

public bool TryCreateShortcut() 
    { 
     String shortcutPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Microsoft\\Windows\\Start Menu\\Programs\\FixSus Toasts Sample .lnk"; 
     if (!File.Exists(shortcutPath)) 
     { 
      InstallShortcut(shortcutPath); 
      return true; 
     } 
     return false; 
    } 

    private void InstallShortcut(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 
     DesktopToastsSample.ShellHelpers.ErrorHelper.VerifySucceeded(newShortcut.SetPath(exePath)); 
     DesktopToastsSample.ShellHelpers.ErrorHelper.VerifySucceeded(newShortcut.SetArguments("")); 

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

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

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

     DesktopToastsSample.ShellHelpers.ErrorHelper.VerifySucceeded(newShortcutSave.Save(shortcutPath, true)); 
    } 

現在,您可以創建一個展示舉杯

// Get a toast XML template 
     XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastImageAndText04); 

     // Fill in the text elements 
     XmlNodeList stringElements = toastXml.GetElementsByTagName("text"); 
     stringElements[1].AppendChild(toastXml.CreateTextNode("Message" + newMessage)); 


     // Specify the absolute path to an image 
     string codeWebFolderPath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, @"..\..\")); 
     String imagePath = "file:///" + Path.GetFullPath(codeWebFolderPath+ "Resources\\FixSus.png"); 
     XmlNodeList imageElements = toastXml.GetElementsByTagName("image"); 
     imageElements[0].Attributes.GetNamedItem("src").NodeValue = imagePath; 

     // Create the toast and attach event listeners 
     ToastNotification toast = new ToastNotification(toastXml); 

     toast.Activated += ToastActivated; 
     toast.Dismissed += ToastDismissed; 
     toast.Failed += ToastFailed; 

     // Show the toast. Be sure to specify the AppUserModelId on your application's shortcut! 
     ToastNotificationManager.CreateToastNotifier(APP_ID).Show(toast); 

APP_ID可以是任何字符串。在我的情況下,它是「NotificationTest.KEY」 注意:不要修改ShellHelper類。 編輯:首先關注Evaldas B的回答,然後應用此解決方案。

相關問題