You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET WPF应用Toast通知点击外部不消失的问题求助

解决WPF NotifyIcon气球提示点击外部不消失的问题

问题分析

你当前使用的NotifyIcon气球提示基于Win32原生控件,当WPF窗口隐藏后,应用消息循环可能无法及时接收系统发送的「点击外部关闭气球」的消息,导致通知无法自动消失。

解决方案

方案一:修复现有NotifyIcon的消息处理

通过重写主窗口WndProc方法,手动处理气球提示的关闭消息,确保应用响应外部点击事件:

  1. 在MainWindow类中添加Win32消息常量声明:
private const int WM_COMMAND = 0x0111;
private const int ID_BALLOON_CLOSE = 0x402;
  1. 重写WndProc处理消息:
protected override void WndProc(ref System.Windows.Forms.Message m)
{
    base.WndProc(ref m);
    
    // 处理气球提示关闭命令
    if (m.Msg == WM_COMMAND && m.WParam.ToInt32() == ID_BALLOON_CLOSE)
    {
        if (m_notifyIcon != null)
        {
            // 强制刷新NotifyIcon状态,确保气球提示消失
            bool wasVisible = m_notifyIcon.Visible;
            m_notifyIcon.Visible = false;
            m_notifyIcon.Visible = wasVisible;
        }
    }
}
  1. 显示气球提示时补充消息处理(可选):
    在调用ShowBalloonTip后添加一行代码,确保未完成的消息被处理:
if (m_notifyIcon != null)
{
    m_notifyIcon.ShowBalloonTip(2000);
    System.Windows.Forms.Application.DoEvents();
}

方案二:改用Windows原生Toast通知(推荐)

现代Windows系统推荐使用ToastNotificationManager发送原生Toast,这类通知默认支持点击外部自动消失,样式更符合系统规范:

  1. 安装NuGet包:Microsoft.Toolkit.Uwp.Notifications
  2. 添加命名空间:
using Windows.UI.Notifications;
using Microsoft.Toolkit.Uwp.Notifications;
  1. 替换原ShowBalloonTip调用为原生Toast显示方法:
private void ShowMinimizedToast()
{
    var toastContent = new ToastContent()
    {
        Visual = new ToastVisual()
        {
            BindingGeneric = new ToastBindingGeneric()
            {
                Children =
                {
                    new AdaptiveText() { Text = "The App" },
                    new AdaptiveText() { Text = "The app has been minimised. Click the tray icon to show." }
                }
            }
        },
        Duration = ToastDuration.Short
    };

    var toast = new ToastNotification(toastContent.GetXml());
    // 替换为自定义应用ID,用于区分通知来源
    ToastNotificationManager.CreateToastNotifier("WpfAppTrayNotifier").Show(toast);
}
  1. 将原代码中m_notifyIcon.ShowBalloonTip(2000);替换为ShowMinimizedToast();即可。

注意事项

  • 方案一需要引用System.Windows.Forms程序集(右键项目→添加引用→框架→勾选System.Windows.Forms)。
  • 方案二仅支持Windows 10及以上系统,兼容性更好且样式更统一。

内容的提问来源于stack exchange,提问作者Kaan Çağhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 13:35:18