首页 新闻 赞助 找找看

winform发送本地 Toast 通知图片无法展示问题?

0
悬赏园豆:10 [已解决问题] 解决于 2023-05-25 10:32

对于未开启Internet 功能的应用,只能使用本地图片,http或https的url是无效的。(原本使用的就是http是的形式)
查询资料就只能用ms-appdata和ms-appx才行了,但winform怎么使用这个啊?
或者有没有其他的办法让图片能成功展示?

https://learn.microsoft.com/zh-cn/windows/apps/design/shell/tiles-and-notifications/send-local-toast?tabs=desktop

        private void ShowToast()
        {
            string title = "featured picture of the day";
            string content = "beautiful scenery";
            string image = "https://picsum.photos/360/180?image=104";
            string logo = "https://picsum.photos/64?image=883";

            string xmlString =
                    $@"<toast><visual>
                   <binding template='ToastGeneric'>
                   <text>{title}</text>
                   <text>{content}</text>
                   <image src='{image}'/>
                   <image src='{logo}' placement='appLogoOverride' hint-crop='circle'/>
                   </binding>
                  </visual></toast>";

            XmlDocument toastXml = new XmlDocument();
            toastXml.LoadXml(xmlString);

            ToastNotification toast = new ToastNotification(toastXml);


            ToastNotificationManager.CreateToastNotifier("Chrome").Show(toast);
        }
问题补充:

winform 是 .net6.0版本

ufo233-的主页 ufo233- | 初学一级 | 园豆:85
提问于:2023-05-24 16:40
< >
分享
最佳答案
0

可以使用 WebClient 类的 DownloadData() 方法将图片下载到本地,然后使用 System.Drawing.Bitmap 类读取图片文件并展示在 ToastNotification 中。

以下是一个示例代码片段:

using System.Net;
using System.Windows.Forms;
using Windows.UI.Notifications;
using Microsoft.Toolkit.Uwp.Notifications;

// ...

// 构造 ToastNotification 对象
ToastContent toastContent = new ToastContentBuilder()
.AddText("Hello, world!")
// 添加图片
.AddInlineImage(new Uri("http://www.xx.com/123.jpg"))
.GetToastContent();

// 下载图片并保存到用户本地硬盘
using (WebClient client = new WebClient())
{
byte[] imageData = client.DownloadData("http://www.xx.com/123.jpg");
using (MemoryStream stream = new MemoryStream(imageData))
{
Bitmap bitmap = new Bitmap(stream);
string imagePath = Path.Combine(Application.LocalUserAppDataPath, "123.jpg");
bitmap.Save(imagePath);

    // 使用 ToastNotificationManager 展示 ToastNotification
    ToastNotification toast = new ToastNotification(toastContent.GetXml())
    {
        Tag = "123",
        Group = "Group",
        Audio = new ToastAudio { Silent = true },
        // 设置本地图片地址
        AppLogoOverride = new Uri($"file:///{imagePath}")
    };
    ToastNotificationManager.CreateToastNotifier("Chrome").Show(toast);
}

}


这个示例中,我们使用 `AddInlineImage()` 方法添加图片,然后使用 `WebClient` 类将图片下载到本地,最后将保存在本地的图片文件地址传给 `AppLogoOverride` 属性展示在 ToastNotification 中。

注意,图片下载成功后需要使用 `using` 关键字释放相关资源。另外,在展示 ToastNotification 时,需要设置 `AppLogoOverride` 属性为 `file:///`+本地图片路径的格式。
收获园豆:10
lanedm | 老鸟四级 |园豆:2378 | 2023-05-25 09:13
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册