![](/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.