.net . NET6通知图标上下文菜单不显示

6za6bjd0  于 2023-02-01  发布在  .NET
关注(0)|答案(1)|浏览(146)

因此,我在.NET 6中构建了一个应用程序,我能够让它在托盘区域显示NotifyIcon,但NotifyIcon上的上下文菜单(右键单击)不会显示。
我按照Implement a menu on tray icon for .NET 5/6 win forms构建了此代码(然后对其进行了更改,使其不使用内联创建,以查看是否导致此问题)
因此,我唯一能想到的是,我的应用程序没有窗体,所以我从Program.cs文件运行此代码。

internal class Program
{
    private static NotifyIcon notifyIcon;
    private static ContextMenuStrip cms;

    private static async Task Main(string[] args)
    {
        notifyIcon = new NotifyIcon();
        notifyIcon.Icon = new Icon("Assets/icon.ico");
        notifyIcon.Text = "Notify";

        cms = new ContextMenuStrip();

        cms.Items.Add(new ToolStripMenuItem("Reconnect", null, new EventHandler(Reconnect_Click)));
        cms.Items.Add(new ToolStripSeparator());
        cms.Items.Add(new ToolStripMenuItem("Quit", null, new EventHandler(Quit_Click), "Quit"));

        notifyIcon.ContextMenuStrip = cms;
        notifyIcon.Visible = true;

        new Thread(() =>
        {
            while (true)
            {
                Thread.Sleep(10000);
                // do application background task
            }
        }).Start();
    }

    protected static void Reconnect_Click(object? sender, System.EventArgs e)
    {
        // do something
    }

    protected static void Quit_Click(object? sender, System.EventArgs e)
    {
        Environment.Exit(0);
    }
}

更新了ContextMenuStrip示例,以便针对未在主上下文/范围中生成的类进行保存

k7fdbhmy

k7fdbhmy1#

您需要有一个消息循环来处理Windows应用程序中使用的Windows消息,以便在操作系统和应用程序的用户界面之间进行通信。
如果你想要一个没有可见窗体但仍然运行消息循环的应用程序,使用Application.Run方法和ApplicationContext对象,然后你也使用上下文来通知应用程序的结束。
样本代码:

internal static class Program
{
    private static NotifyIcon notifyIcon;
    private static ContextMenuStrip cms;
    private static ApplicationContext context;

    [STAThread]
    static void Main()
    {
        ApplicationConfiguration.Initialize();

        notifyIcon = new NotifyIcon();
        notifyIcon.Icon = new Icon("Assets/icon.ico");
        notifyIcon.Text = "Notify";

        cms = new ContextMenuStrip();

        cms.Items.Add(new ToolStripMenuItem("Reconnect", null, new EventHandler(Reconnect_Click)));
        cms.Items.Add(new ToolStripSeparator());
        cms.Items.Add(new ToolStripMenuItem("Quit", null, new EventHandler(Quit_Click), "Quit"));

        notifyIcon.ContextMenuStrip = cms;
        notifyIcon.Visible = true;

        // Create an ApplicationContext and run a message loop
        // on the context.
        context = new ApplicationContext();
        Application.Run(context);

        // Hide notify icon on quit
        notifyIcon.Visible = false;
    }

    static void Reconnect_Click(object? sender, System.EventArgs e)
    {
        MessageBox.Show("Hello World!");
    }

    static void Quit_Click(object? sender, System.EventArgs e)
    {
        // End application though ApplicationContext
        context.ExitThread();
    }
}

相关问题