开发者

Form.HandleCreated Event Never Occurs

开发者 https://www.devze.com 2023-03-05 22:30 出处:网络
As it was requested, I\'ve put up a small internal log viewer for one of my open-source projects (self descriptive image below). While doing so, I had a very strange problem where the newly created wi

As it was requested, I've put up a small internal log viewer for one of my open-source projects (self descriptive image below). While doing so, I had a very strange problem where the newly created window's HandleCreated event does not occur at all. I'm watching this event to make sure that handle is created before invoking any controls.

Form.HandleCreated Event Never Occurs

Below is the problematic code (the static constructor). Does anybody have a workaround for this because none of the usual tricks (like var a = form.Handle;) to force the creation of the handle do not help at all.

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.Resourc开发者_运维技巧es.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 }));
    }
}

Edit: Code is taken from NBug library.


The problem is related to static constructor deadlocks.

0

精彩评论

暂无评论...
验证码 换一张
取 消