如何在Windows气球通知中显示图像



是否可以在Windows气球通知中显示自定义图像/图标?.net框架中的NotifyIcon控件支持气球通知,但它只允许默认图标,如信息、错误等。

如果NotifyIcon不支持这一点,是否有其他API.net框架允许使用自定义图像进行通知?

找到了答案。Windows API支持自定义图标,但托管的.net界面非常简单。Win32 api Shell_NotifyIcon接受NOTIFYCONDATA结构。此结构具有用于设置自定义图标的字段。

    public enum NotifyFlags
    {
        NIF_MESSAGE = 0x01, NIF_ICON = 0x02, NIF_TIP = 0x04, NIF_INFO = 0x10, NIF_STATE = 0x08,
        NIF_GUID = 0x20, NIF_SHOWTIP = 0x80, NIF_REALTIME = 0x40,
    }
    public enum NotifyCommand { NIM_ADD = 0x0, NIM_DELETE = 0x2, NIM_MODIFY = 0x1, NIM_SETVERSION = 0x4 }
    [StructLayout(LayoutKind.Sequential)]
    public struct NOTIFYICONDATA
    {
        public Int32 cbSize;
        public IntPtr hWnd;
        public Int32 uID;
        public NotifyFlags uFlags;
        public Int32 uCallbackMessage;
        public IntPtr hIcon;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
        public String szTip;
        public Int32 dwState;
        public Int32 dwStateMask;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
        public String szInfo;
        public Int32 uVersion;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
        public String szInfoTitle;
        public Int32 dwInfoFlags;
        public Guid guidItem; //> IE 6
        public IntPtr hBalloonIcon;
    }
    [DllImport("shell32.dll")]
    public static extern System.Int32 Shell_NotifyIcon(NotifyCommand cmd, ref NOTIFYICONDATA data);
    private void AddBalloon(string title, string message, Image image)
    {
        NOTIFYICONDATA data = new NOTIFYICONDATA();
        data.cbSize = Marshal.SizeOf(data);
        data.uID = 0x01;
        data.hWnd = Handle;
        data.dwInfoFlags = NIIF_USER;
        data.hIcon = Icon.Handle;
        data.hBalloonIcon = IntPtr.Zero;
        if (message.Image != null)
        {
            data.hBalloonIcon = ((Bitmap)image).GetHicon();
            data.dwInfoFlags |= NIIF_LARGE_ICON;
        }
        data.szInfo = message;
        data.szInfoTitle = title;
        data.uFlags = NotifyFlags.NIF_INFO | NotifyFlags.NIF_SHOWTIP | NotifyFlags.NIF_REALTIME;
        Shell_NotifyIcon(NotifyCommand.NIM_MODIFY, ref data) != 1);
    }

未测试,但您可以更改图标,希望这有帮助吗?

notificationIcon.Icon =  new Icon(Properties.Resources.ResourceManager.GetStream("<Image Location From root>"));

我使用了joyhrs建议:

notificationIcon.Icon =  new Icon(Properties.Resources.ResourceManager.GetStream("<Image Location From root>"));

正如您所说,它不仅在气球顶端显示了新图标,而且还更改了系统托盘中的图标。因此,一个简单的破解方法是添加处理程序

private void notifyIcon_BalloonTipShown(object sender, EventArgs e)

并将系统托盘图标更改回原始图标,从而将气球顶端中的图标设置为新图标。

相关内容

  • 没有找到相关文章

最新更新