任务栏通知不工作:c#

本文关键字:工作 通知 任务栏 | 更新日期: 2023-09-27 18:16:00

我是c#新手。我想写一个程序来显示一个简单的通知。在google上搜索了一些stackoverflow的答案后,我终于写了一个程序。但是这行不通。

代码:

public class SysTrayApp : Form
{
    [STAThread]
    public static void Main()
    {
        Application.Run(new SysTrayApp());
    }
    private NotifyIcon trayIcon;
    private ContextMenu trayMenu;
    public SysTrayApp()
    {
        trayMenu = new ContextMenu(); // Create a simple tray menu with only one item.
        trayMenu.MenuItems.Add("Exit", OnExit);
        trayIcon = new NotifyIcon();
        trayIcon.Text = "MyTrayApp";
        trayIcon.Icon = new Icon("C:''Users''Name''Desktop''test.ico", 40, 40); //origin, width, height
        trayIcon.ContextMenu = trayMenu;
        trayIcon.BalloonTipTitle = "MyTitle";
        trayIcon.BalloonTipText = "This is sample message ";
        trayIcon.ShowBalloonTip(30000);
        trayIcon.Visible = true;
    }
    protected override void OnLoad(EventArgs e)
    {
        Visible = false; // Hide form window.
        ShowInTaskbar = false; // Remove from taskbar.
        base.OnLoad(e);
    }
    private void OnExit(object sender, EventArgs e)
    {
        Application.Exit();
    }
    protected override void Dispose(bool isDisposing)
    {
        if (isDisposing)
        {
            // Release the icon resource.
            trayIcon.Dispose();
        }
        base.Dispose(isDisposing);
    }
}

在任务栏显示图标,但不显示通知。我的要求和这个问题一样

任务栏通知不工作:c#

问题是显示BallonTip的代码驻留在表单的构造函数中。您必须将ShowBallonTip()调用放在一个方法中,该方法在窗体'构造'之后运行。