我的WPF应用程序显示一个窗口,当用户单击一个按钮时,它开始运行其任务并通过上下文菜单最小化到通知区域中的托盘项目,我希望用户能够取消操作
在使用BackgroundWorker之前,上下文菜单已经工作,但是取消没有。由于我已经实现了后台工作程序,因此.runworkerasync()方法运行后,上下文菜单不会出现。
我的通知图标:
<button>Click me!</button>
当我的应用程序运行时,我将其设置为:
public NotifyIcon myNotifyIcon;
然后当用户点击按钮时:
private void setup_NotifyIcon()
{
myNotifyIcon = new NotifyIcon();
setTrayIcon();
myNotifyIcon.MouseDown += new MouseEventHandler(myNotifyIcon_MouseDown);
var menuItemCancel = new MenuItem("Cancel Parsing");
var contextMenu = new ContextMenu();
menuItemCancel.Click += new System.EventHandler(this.menuItemCancel_Click);
contextMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { menuItemCancel });
myNotifyIcon.ContextMenu = contextMenu;
}
private void menuItemCancel_Click(object Sender, EventArgs e)
{
//do something
}
void myNotifyIcon_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
//do something
}
}
为什么赢得myNotifyIcon.MouseDown + = new MouseEventHandler(myNotifyIcon_MouseDown);触发上下文菜单?
答案 0 :(得分:2)
解决方案证明是塞巴斯蒂安在评论中提出的一个线程问题。
关键是使用Application.Run()在另一个线程上启动图标,并使该图标中的图标可见。
完成此操作后,右键单击图标即可,正如正在处理的取消功能一样。
private void setup_NotifyIcon()
{
Thread notifyThread = new Thread(
delegate ()
{
myNotifyIcon = new NotifyIcon();
setTrayIcon();
myNotifyIcon.MouseDown += new MouseEventHandler(myNotifyIcon_MouseDown);
mnuCancel = new MenuItem("Cancel Parsing");
menu = new ContextMenu();
mnuCancel.Click += new System.EventHandler(menuItemCancel_Click);
menu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { mnuCancel });
myNotifyIcon.ContextMenu = menu;
myNotifyIcon.BalloonTipIcon = System.Windows.Forms.ToolTipIcon.Info; //Shows the info icon so the user doesn't thing there is an error.
myNotifyIcon.BalloonTipText = "The P6 Parser will minimize to the system tray while working.";
myNotifyIcon.BalloonTipTitle = "Processing...";
myNotifyIcon.Visible = true;
myNotifyIcon.ShowBalloonTip(500);
myNotifyIcon.Visible = true;
System.Windows.Forms.Application.Run();
});
notifyThread.Start();
}
答案 1 :(得分:-2)
在 Program.cs 中将 Annotation [STAThread] 更改为 [MTAThread]