防止C#程序出现多个系统托盘图标

3
我正在开发一个C#.net应用程序,我正在编写代码以在系统托盘中显示图标。每当有新消息到达时,气球提示将显示在那里,并带有单击事件,可以打开新的消息。一切都很正常,但问题是我在系统托盘中生成了多个图标,而应该只有一个。如何防止这种情况?我在互联网上找到了如何处理它们,但找不到防止多个图标的方法。还是有更好的方法来显示新收到的消息通知吗?如果您知道解决方案,请帮助我。

可能需要一点代码帮助。 - lc.
你的代码中创建图标的部分在哪里? - Lee Taylor
1个回答

2

有更好的自定义解决方案可用,可以在这里这里查看一些示例。

然而,系统托盘不会自动刷新。如果您显示/隐藏多个系统托盘图标,它可能会搞乱托盘。通常,当您将鼠标悬停在所有已处理的图标上时,它们都会消失。但是,有一种方法可以通过编程方式刷新系统托盘。参考这里

注意:SendMessage函数向窗口或窗口发送指定消息。 SendMessage函数调用指定窗口的窗口过程,并且直到窗口过程处理了该消息后才返回。

 [StructLayout(LayoutKind.Sequential)]
    public struct RECT
    {
        public int left;
        public int top;
        public int right;
        public int bottom;
    }
    [DllImport("user32.dll")]
    public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    [DllImport("user32.dll")]
    public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
    [DllImport("user32.dll")]
    public static extern bool GetClientRect(IntPtr hWnd, out RECT lpRect);
    [DllImport("user32.dll")]
    public static extern IntPtr SendMessage(IntPtr hWnd, uint msg, int wParam, int lParam);


    public void RefreshTrayArea()
    {
        IntPtr systemTrayContainerHandle = FindWindow("Shell_TrayWnd", null);
        IntPtr systemTrayHandle = FindWindowEx(systemTrayContainerHandle, IntPtr.Zero, "TrayNotifyWnd", null);
        IntPtr sysPagerHandle = FindWindowEx(systemTrayHandle, IntPtr.Zero, "SysPager", null);
        IntPtr notificationAreaHandle = FindWindowEx(sysPagerHandle, IntPtr.Zero, "ToolbarWindow32", "Notification Area");
        if (notificationAreaHandle == IntPtr.Zero)
        {
            notificationAreaHandle = FindWindowEx(sysPagerHandle, IntPtr.Zero, "ToolbarWindow32", "User Promoted Notification Area");
            IntPtr notifyIconOverflowWindowHandle = FindWindow("NotifyIconOverflowWindow", null);
            IntPtr overflowNotificationAreaHandle = FindWindowEx(notifyIconOverflowWindowHandle, IntPtr.Zero, "ToolbarWindow32", "Overflow Notification Area");
            RefreshTrayArea(overflowNotificationAreaHandle);
        }
        RefreshTrayArea(notificationAreaHandle);
    }


    private static void RefreshTrayArea(IntPtr windowHandle)
    {
        const uint wmMousemove = 0x0200;
        RECT rect;
        GetClientRect(windowHandle, out rect);
        for (var x = 0; x < rect.right; x += 5)
            for (var y = 0; y < rect.bottom; y += 5)
                SendMessage(windowHandle, wmMousemove, 0, (y << 16) + x);
    }

非常感谢您的回复,但是您能告诉我在哪里放置这段代码以及如何调用它吗? - Software_developer
@软件开发人员:很可能是在显示通知的类中。在显示新通知之前或之后,刷新任务栏。 - CharithJ

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接