Files
auto-shutdown/Services/NotificationService.cs
home-PC d2d81a482b feat(app): 初始化自动关机工具首个版本
实现基于 WPF 的 AutoShutdown 主界面,支持关机、重启、睡眠、休眠、唤醒、锁屏和注销等电源任务。

支持指定时间和倒计时计划、执行前提醒、系统关机撤销、Windows 唤醒任务、托盘运行、自定义图标以及 OmniNotify 通知适配。

修复关闭到托盘时的运行提醒,并支持单击托盘图标打开或收起主界面。

补充 README、发布配置和 win-x64 Release 输出要求。

Release: win-x64
2026-05-18 23:54:58 +08:00

93 lines
2.5 KiB
C#

using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Windows;
using AutoShutdown.Models;
namespace AutoShutdown.Services;
internal sealed class NotificationService
{
private static readonly HttpClient HttpClient = new();
private NotificationSettings _settings;
public NotificationService(NotificationSettings settings)
{
_settings = settings;
}
public void UpdateSettings(NotificationSettings settings)
{
_settings = settings;
}
public async Task NotifyAsync(Window owner, string title, string body, MessageBoxImage image = MessageBoxImage.Information)
{
if (_settings.Mode == NotificationMode.OmniNotify)
{
await TrySendToOmniNotifyAsync(title, body);
return;
}
System.Windows.MessageBox.Show(owner, body, title, MessageBoxButton.OK, image);
}
public Task NotifyAsync(string title, string body)
{
return _settings.Mode == NotificationMode.OmniNotify
? TrySendToOmniNotifyAsync(title, body)
: Task.CompletedTask;
}
public async Task<bool> TestOmniNotifyAsync(NotificationSettings settings)
{
var oldSettings = _settings;
try
{
_settings = settings;
await SendToOmniNotifyAsync("AutoShutdown 测试消息", "OmniNotify 适配已连接。");
return true;
}
catch
{
return false;
}
finally
{
_settings = oldSettings;
}
}
private async Task SendToOmniNotifyAsync(string title, string body)
{
if (!Uri.TryCreate(_settings.OmniNotifyEndpoint, UriKind.Absolute, out var endpoint))
{
return;
}
var payload = JsonSerializer.Serialize(new
{
channel = string.IsNullOrWhiteSpace(_settings.Channel) ? "default" : _settings.Channel.Trim(),
title,
body
});
using var content = new StringContent(payload, Encoding.UTF8, "application/json");
using var response = await HttpClient.PostAsync(endpoint, content);
response.EnsureSuccessStatusCode();
}
private async Task TrySendToOmniNotifyAsync(string title, string body)
{
try
{
await SendToOmniNotifyAsync(title, body);
}
catch
{
// OmniNotify 适配模式下不再弹窗打扰用户,发送失败只静默跳过。
}
}
}