2011-09-04 80 views
0

我已經在過去的一週中使用了這個問題,這是我的和平!請幫忙... EventArrivedEventHandler被困在一個循環中,如果我阻止它,那麼它不會捕獲事件。但是當我使用一個處理程序方法時,線程仍然集中在循環中,並且不會關注我想要在處理程序中創建的新窗體!奇怪的是,如果我只是使用一些小的東西,比如一個MessageBox,它不會引起問題,只是嘗試實例化一個表單會導致按鈕無法繪製。然後在程序停止響應後不久。如果你想知道表單代碼的位置,它只是一個由.NET創建的標準表單,除了在事件處理程序中,它可以在代碼中的其他任何地方工作。c#EventArrivedEventHandler陷入無限循環,無法引用觀察者

謝謝!

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 
    } 
} 

回答

0

我的猜測是,該ManagementEventWatcher調用從不同的線程比UI線程EventArrived處理程序。然後在該線程上執行您的showPrintingForm,並從UI線程以外的其他線程訪問UI。你需要將你的代碼編組回你的UI線程。

+0

@ Chris,真棒,你的提示引導我用Application.Run(new Form1())開始我的表單;它應該啓動,謝謝! – Agonz