![](/img/trans.png)
[英]Right clicking notifyicon in system tray does not show contextmenu
[英].NET6 NotifyIcon ContextMenu wont show
所以我在 .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 实例以针对未在主上下文/作用域中构建的 class 进行保存
您需要有一个消息循环来处理 Windows 消息,这些消息在 Windows 应用程序中使用,以便在操作系统和应用程序的用户界面之间进行通信。
如果您想要一个没有可见表单但仍运行消息循环的应用程序,请使用Application.Run
方法和ApplicationContext
object。然后您还可以使用上下文来表示应用程序结束。
示例代码:
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.