2011-05-13 62 views
1

按照要求,我爲我的一個開放源代碼項目(下面的自描述圖像)提供了一個小型內部日誌查看器。在這樣做的時候,我有一個非常奇怪的問題,那就是新創建的窗口的HandleCreated事件根本沒有發生。我正在觀看此事件,以確保在調用任何控件之前創建了句柄。Form.HandleCreated事件從不發生

NBug Internal Log Viewer

下面是有問題的代碼(靜態構造)。有沒有人有這方面的解決方法,因爲沒有任何常用的技巧(如var a = form.Handle;)強制創建句柄根本沒有任何幫助。

internal partial class InternalLogViewer : Form 
{ 
    static InternalLogViewer() 
    { 
     viewer = new InternalLogViewer(); 
     formShown = new ManualResetEvent(false); 
     viewer.HandleCreated += (sender, e) => formShown.Set(); 
     Task.Factory.StartNew(() => viewer.ShowDialog()); 
     formShown.WaitOne(); // ToDo: This needs a workaround as it waits for an eternity 
    } 

    private static InternalLogViewer viewer; 
    private static ManualResetEvent formShown; 

    public static void LogEntry(string message, LoggerCategory category) 
    { 
     viewer.Invoke((MethodInvoker)delegate 
     { 
      viewer.InternalLogEntry(message, category); 
     }); 
    } 

    internal InternalLogViewer() 
    { 
     InitializeComponent(); 
     this.Icon = Properties.Resources.NBug_icon_16; 
     this.notifyIcon.Icon = Properties.Resources.NBug_icon_16; 
    } 

    internal void InternalLogEntry(string message, LoggerCategory category) 
    { 
     this.loggerListView.Items.Add(new ListViewItem(new[] { category.ToString().Remove(0, 4), DateTime.Now.ToString("HH:mm:ss"), message })); 
    } 
} 

編輯:代碼取自NBug庫。

+4

可能與以下內容有關:http://blogs.msdn.com/b/pfxteam/archive/2011/05/03/10159682.aspx – Dmitry 2011-05-13 13:00:24

+0

哦,我將靜態構造函數的內容移動到一個單獨的函數中,並調用爲初始化實際上工作。我真的無法想象這樣的僵局! – 2011-05-13 13:15:48

+0

@Dmitry:看起來像您找到了解決方案,請將其作爲下面的「答案」發佈,以便讀者知道這是一個很好的答案。 – 2011-05-13 23:12:06

回答