使用c#控制台应用程序的系统任务栏图标不会显示菜单 [英] System tray icon with c# Console Application won't show menu
问题描述
我有一个小的C#(.NET 4.0)控制台应用程序,我希望用户能够通过右键单击系统任务栏图标显示菜单来进行交互。我可以毫无问题地向托盘添加一个图标,但是我无法使菜单出现。我正在使用以下代码:
I've got a small C# (.NET 4.0) Console Application that I'd like the user to be able to interact by showing a menu when they right-click the System Tray icon. I can add an icon to the Tray with no problems, but I just cannot get the menu to appear. I'm using the following code:
NotifyIcon trayIcon = new NotifyIcon();
trayIcon.Text = "TestApp";
trayIcon.Icon = new Icon(SystemIcons.Application, 40, 40);
ContextMenu trayMenu = new ContextMenu();
trayMenu.MenuItems.Add("Blah", item1_Click);
trayMenu.MenuItems.Add("Blah2", item1_Click);
trayMenu.MenuItems.Add("Blah3", item1_Click);
trayIcon.ContextMenu = trayMenu;
trayIcon.Visible = true;
...这会将图标放入托盘。但是,右键单击该图标不会执行任何操作。我尝试了 MenuItems.Add
的各种排列,但是没有任何东西会使菜单出现。我确定我缺少简单的东西-有什么想法吗?
... which puts the icon in the tray. However, right-clicking the icon does nothing. I've tried various permutations of MenuItems.Add
, but nothing will make the menu appear. I'm sure I'm missing something simple - any ideas what?
推荐答案
在创建图标后尝试添加以下内容:
Try adding this after you create the icon:
Application.Run()
请注意,此方法将不会返回,因此调用后将无法执行任何操作。这意味着您将必须在单独的线程中完成所有其他工作。
Note that this method will not return, so you can't do anything after calling it. This means that you'll have to do all your other work in a separate thread.
发生的事情是,操作系统向您的应用程序发送了一条消息,告诉它托盘图标已被右键单击,但是任务栏图标代码从未看到它(因为这些消息由 Application.Run
处理),因此无法通过打开菜单进行响应。
What happens is that the OS sends your application a message telling it that the tray icon has been right-clicked, but the tray icon code never sees it (because these messages are processed by Application.Run
) and so can't respond by opening the menu.
这篇关于使用c#控制台应用程序的系统任务栏图标不会显示菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!