获取 Windows 通知中心弹窗通知内容(含工具汉化)

目录

前言

技术原理概述

测试代码和程序下载连接


本文出处链接:https://blog.csdn.net/qq_59075481/article/details/136440280。

前言

从 Windows 8.1 开始,Windows 通知现在以 Toast 而非 Balloon 形式显示( Bollon 通知其实现在是应用通知的一个子集),并记录在通知中心中。到目前为止,为了检索通知的内容,您必须抓取窗口的句柄并尝试读取它的文本内容,或者其他类似的东西。

特别是在 Toast 可用之后,这样做变得很困难,但从 Windows 10 Anniversary Edition (10.0.14393.0) 版本开始, MS 实现了“通知监听器” API(UserNotificationListener),允许您以与获取 Android 通知相同的方式获取 Windows 通知。

Toast 通知

技术原理概述

参考 gpsnmeajp 的代码思路,

(原文翻译:https://blog.csdn.net/qq_59075481/article/details/136433878)

我们使用 UserNotificationListener 这个 WinRT API 来监视系统通知区域的弹窗。该 API 不仅可以拦截 Toast 通知(应用通知),而且可以拦截旧式的 Balloon 通知。

Balloon 通知

下面是异步获取消息的处理代码(await 异步关键字在 C++ 中没有,需要额外的自己构建处理模式,所以一般代码使用 C#):

首先,我们只关心前三个字段 id、title 和 body。title 是通知的标题,body 是通知的内容。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Windows.Forms;
using Windows.UI.Notifications.Management;
using Windows.Foundation.Metadata;
using Windows.UI.Notifications;namespace NotificationListenerThrower
{class NotificationMessage{public uint id { get; set; }public string title { get; set; }public string body { get; set; }public NotificationMessage(uint id, string title, string body) {this.id = id;this.title = title != null ? title : "";this.body = body != null ? body : "";}}
}

获取消息的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Windows.Forms;
using Windows.UI.Notifications.Management;
using Windows.Foundation.Metadata;
using Windows.UI.Notifications;namespace NotificationListenerThrower
{class Notification{bool accessAllowed = false;UserNotificationListener userNotificationListener = null;public async Task<bool> Init(){if (!ApiInformation.IsTypePresent("Windows.UI.Notifications.Management.UserNotificationListener")){accessAllowed = false;userNotificationListener = null;return false;}userNotificationListener = UserNotificationListener.Current;UserNotificationListenerAccessStatus accessStatus = await userNotificationListener.RequestAccessAsync();if (accessStatus != UserNotificationListenerAccessStatus.Allowed) {accessAllowed = false;userNotificationListener = null;return false;}accessAllowed = true;return true;}public async Task<List<NotificationMessage>> Get(){if (!accessAllowed) {return new List<NotificationMessage>();}List<NotificationMessage> list = new List<NotificationMessage>();IReadOnlyList<UserNotification> userNotifications = await userNotificationListener.GetNotificationsAsync(NotificationKinds.Toast);foreach (var n in userNotifications){var notificationBinding = n.Notification.Visual.GetBinding(KnownNotificationBindings.ToastGeneric);if (notificationBinding != null){IReadOnlyList<AdaptiveNotificationText> textElements = notificationBinding.GetTextElements();string titleText = textElements.FirstOrDefault()?.Text;string bodyText = string.Join("\n", textElements.Skip(1).Select(t => t.Text));list.Add(new NotificationMessage(n.Id, titleText, bodyText));}}return list;}}}

gpsnmeajp 通过将功能写入 ListBox 和转发到 WebSocket 实现向远程客户端分发通知的信息。

NotificationListenerThrower 作为中间人获取 Windows 通知中心的消息内容,并通过 WebSocket 向客户端转发消息内容( 模式-> 外模式)。

软件组织逻辑

下面是该工具的 WebSocket 前/后端实现。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Windows.Forms;
using Windows.UI.Notifications.Management;
using Windows.Foundation.Metadata;
using Windows.UI.Notifications;namespace NotificationListenerThrower
{class Websocket{HttpListener httpListener = null;Task httpListenerTask = null;List<WebSocket> WebSockets = new List<WebSocket>();bool localOnly = false;bool viewer = false;public void Open(string port, bool localOnly, bool viewer) {this.localOnly = localOnly;this.viewer = viewer;string host = localOnly ? "127.0.0.1" : "+";httpListener = new HttpListener();httpListener.Prefixes.Add("http://" + host + ":" + port + "/");httpListener.Start();//接続待受タスクhttpListenerTask = new Task(async () => {try{while (true){HttpListenerContext context = await httpListener.GetContextAsync();if (localOnly == true && context.Request.IsLocal == false){context.Response.StatusCode = 400;context.Response.Close(Encoding.UTF8.GetBytes("400 Bad request"), true);continue;}if (!context.Request.IsWebSocketRequest){if (viewer){context.Response.StatusCode = 200;context.Response.Close(Encoding.UTF8.GetBytes(html), true);}else {context.Response.StatusCode = 404;context.Response.Close(Encoding.UTF8.GetBytes("404 Not found"), true);}continue;}if (WebSockets.Count > 1024){context.Response.StatusCode = 503;context.Response.Close(Encoding.UTF8.GetBytes("503 Service Unavailable"), true);continue;}HttpListenerWebSocketContext webSocketContext = await context.AcceptWebSocketAsync(null);WebSocket webSocket = webSocketContext.WebSocket;if (localOnly == true && webSocketContext.IsLocal == false){webSocket.Abort();continue;}WebSockets.Add(webSocket);}}catch (HttpListenerException){//Do noting (Closed)}});httpListenerTask.Start();}public async Task Broadcast(string msg) {ArraySegment<byte> arraySegment = new ArraySegment<byte>(Encoding.UTF8.GetBytes(msg));foreach (var ws in WebSockets){try{if (ws.State == WebSocketState.Open){await ws.SendAsync(arraySegment, WebSocketMessageType.Text, true, CancellationToken.None);}else{ws.Abort();}}catch (WebSocketException){//Do noting (Closed)}}WebSockets.RemoveAll(ws => ws.State != WebSocketState.Open);}public void Close() {foreach (var ws in WebSockets){ws.Abort();ws.Dispose();}WebSockets.Clear();try{httpListener?.Stop();}catch (Exception) { //Do noting}httpListenerTask?.Wait();httpListenerTask?.Dispose();}public int GetConnected() {return WebSockets.Count;}string html = @"<html>
<head>
<meta charset='UTF-8'/>
<meta name='viewport' content='width=device-width,initial-scale=1'>
</head>
<body>
<input id='ip' value='ws://127.0.0.1:8000'></input>
<button onclick='connect();'>开始连接</button>
<button onclick='disconnect();'>取消连接</button>
<div id='ping'></div>
<div id='log'></div>
<script>
let socket = null;
let lastupdate = new Date();window.onload = function() {document.getElementById('ip').value = 'ws://'+location.host;connect();
};
function connect(){try{if(socket != null){socket.close();}socket = new WebSocket(document.getElementById('ip').value);socket.addEventListener('error', function (event) {document.getElementById('log').innerText = '连接失败';	});socket.addEventListener('open', function (event) {document.getElementById('log').innerText = '持续连接中...';	});socket.addEventListener('message', function (event) {let packet = JSON.parse(event.data);if('ping' in packet){lastupdate = new Date();document.getElementById('ping').innerText = 'ping: '+lastupdate;}else{document.getElementById('log').innerText = packet.id +':'+packet.title+':'+packet.body +'\n'+ document.getElementById('log').innerText;}});socket.addEventListener('onclose', function (event) {document.getElementById('log').innerText = document.getElementById('log').innerText +'\n' +'CLOSED';socket.close();socket = null;});}catch(e){document.getElementById('log').innerHTML = e;	}
}
function disconnect(){socket.close();socket = null;document.getElementById('log').innerText = '正在连接';	
}
function timeout(){if(new Date().getTime() - lastupdate.getTime() > 3000){if(socket != null){document.getElementById('ping').innerText = 'ping: 超时! 正在重新连接...';disconnect();connect();}else{document.getElementById('ping').innerText = 'ping: 超时!';}}
}
setInterval(timeout,1000);</script>
</body>
</html>";}
}

应用程序及后端代码如下。其中在 WatchTimer_Tick 方法内修复了使用默认参数调用 JsonSerializer 在序列化文本时,编码错误的问题。这使得中文文本可以正常显示在应用程序中。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.IO;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Windows.Forms;
using System.Text.Json;
using System.Text.Json.Serialization;namespace NotificationListenerThrower
{public partial class Form1 : Form{class Setting {public string port { get; set; }public bool localonly { get; set; }public bool viewer{ get; set; }}Websocket websocket = new Websocket();Notification notification = new Notification();uint sent = 0;public Form1(){InitializeComponent();}private async void Form1_Load(object sender, EventArgs e){if (!await notification.Init()){PresentTextBox.Text = "载入中";PresentTextBox.BackColor = Color.Red;return;}PresentTextBox.Text = "就绪";PresentTextBox.BackColor = Color.Green;open(load());}private void Form1_FormClosed(object sender, FormClosedEventArgs e){websocket.Close();}List<NotificationMessage> lastNotificationMessage = new List<NotificationMessage>();private async void WatchTimer_Tick(object sender, EventArgs e){List<NotificationMessage> notificationMessage = await notification.Get();DetectedListBox.Items.Clear();foreach (var n in notificationMessage){// 使用 UnsafeRelaxedJsonEscaping 编码器,// 它会在 JSON 字符串中对非 ASCII 字符进行逃逸处理,// 以确保正确的序列化。var options = new JsonSerializerOptions{Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping};string msg = JsonSerializer.Serialize(n, options);// 支持中文编码DetectedListBox.Items.Add(msg);if (lastNotificationMessage.Where(l => l.id == n.id).Count() == 0) {// 新建await websocket.Broadcast(msg);sent = unchecked(sent + 1);}}lastNotificationMessage = notificationMessage;SendTextBox.Text = sent.ToString();}private async void PingTimer_Tick(object sender, EventArgs e){ConnectedTextBox.Text = websocket.GetConnected().ToString();await websocket.Broadcast("{\"ping\":true}");}private void ApplyButton_Click(object sender, EventArgs e){open(save());}private Setting load(){Setting setting;if (File.Exists("setting.json")){string json = File.ReadAllText("setting.json");try{setting = JsonSerializer.Deserialize<Setting>(json);PortTextBox.Text = setting.port;LocalOnlyCheckBox.Checked = setting.localonly;ViewerCheckBox.Checked = setting.viewer;return setting;}catch (JsonException){//Do noting (json error)}}setting = new Setting{port = PortTextBox.Text,localonly = LocalOnlyCheckBox.Checked,viewer = ViewerCheckBox.Checked};return setting;}private Setting save(){Setting setting = new Setting{port = PortTextBox.Text,localonly = LocalOnlyCheckBox.Checked,viewer = ViewerCheckBox.Checked};string json = JsonSerializer.Serialize(setting);File.WriteAllText("setting.json", json);return setting;}private void open(Setting setting){AccessStatusTextBox.Text = "CLOSED";AccessStatusTextBox.BackColor = Color.Red;websocket.Close();try{websocket.Open(setting.port, setting.localonly, setting.viewer);}catch (HttpListenerException e) {MessageBox.Show(e.Message);return;}AccessStatusTextBox.Text = "OPEN";AccessStatusTextBox.BackColor = Color.Green;}}
}

这款软件的汉化界面如下图:

NotificationListenerThrower 工具界面

网页测试界面: 

网页端接收的消息

测试代码和程序下载连接

可以在 Github 上获取原版(不支持友好的中文输入输出)

https://github.com/gpsnmeajp/NotificationListenerThrower?tab=readme-ov-file

或者使用我修复并汉化后的版本:

1. NotificationListenerThrower_0.01_Repack(源代码):

        链接:https://wwz.lanzouo.com/iOESN1q7r1cf        密码:2ym3

2. NotificationListenerThrower-Net6.0_x64_10.0.19041.0(可执行文件):

        链接:https://wwz.lanzouo.com/iGFG11q7r21a        密码:5bcw


本文出处链接:https://blog.csdn.net/qq_59075481/article/details/136440280。

发布于:2024.03.03,更新于:2024.03.03.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/508617.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

第二证券:富时罗素扩容 A股引入国际增量资金

日前&#xff0c;英国富时罗素指数公司&#xff08;FTSE Russell&#xff0c;简称“富时罗素”&#xff09;公布的全球股票指数&#xff08;FTSE Global Equity Index Series&#xff09;半年度指数检查陈述显现&#xff0c;将新调入A股76只、调出1只。此前&#xff0c;富时罗素…

【Git】深入理解 Git 分支合并操作:git merge dev 命令详解

深入理解 Git 合并操作&#xff1a;git merge dev 命令详解 摘要&#xff1a;本文将深入探讨 Git 中的合并操作&#xff0c;以及如何使用 git merge dev 命令将dev 分支的修改合并到当前分支&#xff08;假设当前分支为main 分支&#xff09;中。通过详细的解释和示意图&#x…

【Java项目介绍和界面搭建】拼图小游戏——键盘、鼠标事件

&#x1f36c; 博主介绍&#x1f468;‍&#x1f393; 博主介绍&#xff1a;大家好&#xff0c;我是 hacker-routing &#xff0c;很高兴认识大家~ ✨主攻领域&#xff1a;【渗透领域】【应急响应】 【Java】 【VulnHub靶场复现】【面试分析】 &#x1f389;点赞➕评论➕收藏 …

后端开发技术面试指南

工作10多年&#xff0c;每年都会帮组里面试一些新同学校招社招的都有&#xff0c;下面我就从一个面试官的视角来给大家拆解一下如何淡然应对后端开发技术面试。 1.一面多为电话面试 (1)问七问八 ①简历要注重内容&#xff0c;形式上不丑没有错别字即可。之前收到过一个工作5…

【计算机考研】408学到什么程度才能考130?

408考130要比考研数学考130难的多 我想大部分考过408的考生都是这么认为的。408的难点在于他涉及的范围太广了&#xff0c;首先如果你要备考408&#xff0c;你要准备四门课程&#xff0c;分别是数据结构&#xff0c;计算机组成原理&#xff0c;操作系统和计算机网络。 这四门…

kafka进阶(二)

文章目录 前言一、Ack机制二、ISR集合总结 前言 本篇主要介绍kafka 的 Ack机制 和 ISR集合 一、Ack机制 Kafka提供了三种不同的应答机制&#xff08;ACK&#xff09;&#xff1a; acks0&#xff1a;这是最不可靠的模式。在这种模式下&#xff0c;生产者不会等待来自服务器的…

PHP【swoole】

前言 Swoole官方文档&#xff1a;Swoole 文档 Swoole 使 PHP 开发人员可以编写高性能高并发的 TCP、UDP、Unix Socket、HTTP、 WebSocket 等服务&#xff0c;让 PHP 不再局限于 Web 领域。Swoole4 协程的成熟将 PHP 带入了前所未有的时期&#xff0c; 为性能的提升提供了独一无…

wordpress 开源主题

海外就医wordpress主题 出国看病、海外就医是越来越多中产家庭的选择&#xff0c;此wordpress主题适合做相关业务的公司官网。 https://www.jianzhanpress.com/?p5220 防护wordpress外贸主题 个人防护器具wordpress外贸主题&#xff0c;适合做劳动保护的外贸公司使用。 ht…

matplotlib散点图

matplotlib散点图 假设通过爬虫你获取到了北京2016年3, 10月份每天白天的最高气温(分别位于列表a, b), 那么此时如何寻找出气温和随时间(天)变化的某种规律? from matplotlib import pyplot as pltx_3 range(1, 32) x_10 range(51, 82)y_3 [11,17,16,11,12,11,12,6,6,7,8…

CentOS配网报错:network is unreachable

常用命令&#xff1a; 打开&#xff1a; cd /etc/sysconfig/network-scripts/ 修改&#xff1a; vim ifcfg-ens33 打开修改&#xff1a; vim /etc/sysconfig/network-scripts/ifcfg-ens33 保存&#xff1a; 方法1&#xff1a;ESCZZ&#xff08;Z要大写&#xff09; 方…

2024绿色能源、城市规划与环境国际会议(ICGESCE 2024)

2024绿色能源、城市规划与环境国际会议(ICGESCE 2024) 一、【会议简介】 随着全球气候变化和环境问题日益严重&#xff0c;绿色能源和可持续发展已成为全球关注的焦点。本次会议旨在汇聚全球在绿色能源、城市规划与环境领域的专家、学者和实践者&#xff0c;共同探讨和分享关于…

ChatGPT最新功能“Text To Speech (TTS,文本转语音)”详细解读!

大家好&#xff0c;我是木易&#xff0c;一个持续关注AI领域的互联网技术产品经理&#xff0c;国内Top2本科&#xff0c;美国Top10 CS研究生&#xff0c;MBA。我坚信AI是普通人变强的“外挂”&#xff0c;所以创建了“AI信息Gap”这个公众号&#xff0c;专注于分享AI全维度知识…