c# EventArrivedEventHandler陷入无限循环,无法引用监视器
本文关键字:引用 监视器 无限循环 EventArrivedEventHandler | 更新日期: 2023-09-27 18:07:21
过去一周我都在谷歌上搜索这个问题,它让我心神不宁!请帮助……EventArrivedEventHandler被困在循环中,如果我停止它,它就不会捕获事件。但是当我使用处理程序方法时,线程仍然集中在循环上,并且不会关注我试图在处理程序中创建的新形式!奇怪的是,如果我只是使用一些小的东西,像一个MessageBox,它不会引起问题,只是试图实例化一个表单导致按钮不画。然后在程序停止响应后不久。如果你想知道表单代码在哪里,它只是一个标准的表单由。net,工作在代码的其他地方,除了在事件处理程序。
谢谢!
class MainClass
{
public static void Main()
{
TaskIcon taskbarIcon;
EventWatch myWatcher;
taskbarIcon = new TaskIcon();
taskbarIcon.Show();
myWatcher = new EventWatch();
myWatcher.Start();
Application.Run();
}
}
public class TaskIcon
{
public void Show()
{
NotifyIcon notifyIcon1 = new NotifyIcon();
ContextMenu contextMenu1 = new ContextMenu();
MenuItem menuItem1 = new MenuItem();
MenuItem menuItem2 = new MenuItem();
contextMenu1.MenuItems.AddRange(new MenuItem[] { menuItem1, menuItem2 });
menuItem1.Index = 0;
menuItem1.Text = "Settings";
menuItem1.Click += new EventHandler(notifyIconClickSettings);
menuItem2.Index = 1;
menuItem2.Text = "Exit";
menuItem2.Click += new EventHandler(notifyIconClickExit);
notifyIcon1.Icon = new Icon("app.ico");
notifyIcon1.Text = "Print Andy";
notifyIcon1.ContextMenu = contextMenu1;
notifyIcon1.Visible = true;
}
private static void notifyIconClickSettings(object Sender, EventArgs e)
{
MessageBox.Show("Settings Here");
}
private static void notifyIconClickExit(object Sender, EventArgs e)
{
//taskbarIcon.Visible = false; // BONUS QUESTION: Why can't I hide the tray icon before exiting?
Application.Exit();
}
}
public class EventWatch
{
public void Start()
{
string thisUser = WindowsIdentity.GetCurrent().Name.Split('''')[1];
WqlEventQuery query = new WqlEventQuery();
query.EventClassName = "__InstanceCreationEvent";
query.Condition = @"TargetInstance ISA 'Win32_PrintJob'";
query.WithinInterval = new TimeSpan(0, 0, 0, 0, 1);
ManagementScope scope = new ManagementScope("root''CIMV2");
scope.Options.EnablePrivileges = true;
ManagementEventWatcher watcher = new ManagementEventWatcher(scope, query);
watcher.EventArrived += new EventArrivedEventHandler(showPrintingForm);
watcher.Start();
}
void showPrintingForm(object sender, EventArrivedEventArgs e)
{
// MessageBox.Show("This will draw just fine");
Form1 myForm;
myForm = new Form1();
myForm.Show(); // This causes a hangup
}
}
我的猜测是ManagementEventWatcher
从不同于UI线程的线程调用EventArrived
处理程序。然后你的showPrintingForm
在该线程上执行,从不同的线程访问UI,而不是UI线程是坏的。您需要将代码封送回UI线程。