Question

I'm trying to show window when user need to be notify about some work to do. Every think work fine, but i want to show form absolute topmost. I set form property TopMost = true but it does not work, window still show behind other forms.

I figure out that TopMost = true don't work only with BackgroundWorker, when i use Timer class it work fine. I'm wonder why? Anybody can explain me this?

Here is simple example what i want to do.

    static void Main(string[] args)
    {
        try
        {
            BackgroundWorker worker = new BackgroundWorker();

            worker.DoWork += new DoWorkEventHandler(worker_DoWork);
            worker.RunWorkerAsync();

            Application.Run(new Form());
        }
        catch (Exception exp)
        {
            Console.WriteLine(exp);
        }

    }

    static void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        while (true)
        {
            System.Threading.Thread.Sleep(1000);

            if (NeedNotify())
            {
                NotifyForm myNotifyForm = new NotifyForm();

                myNotifyForm.TopMost = true;
                myNotifyForm.ShowDialog(); // NotifyForm still show behind others windows
            }
        }
    }

    private static bool NeedNotify()
    {
        return true;
    }
}
Was it helpful?

Solution

Creating the form within the background worker causes the form to be created on a different thread. Instead, create and show the form in your main thread before calling RunWorkerAsync.

Another problem may arise from the fact that you're creating the "notification" before the application's main loop is even started. You may consider reorganizing your code so that the background worker is started from the main form's OnLoad event.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top