Quantcast
Channel: Windows Forms General forum
Viewing all articles
Browse latest Browse all 12583

How can I show a Messagebox on top of my worker-threaded splash screen?

$
0
0

Hi,

My Windows Forms app shows a splash screen that is created on a worker thread in program.cs. Before showing the MainForm in it, I need to do a lot of stuff that includes showing error messages by using MessageBox.Show() functions. The problem is that the MessageBox window is displayed behind the splash screen. It behaves as expected when running with the Visual Studio debugger for some reason. I'd appreciate it if someone would let me know how I can show the message box on top of the splash screen. Below shows the repro steps:

  1. Start Visual Studio.
  2. Create a new Windows Forms app in C#.
  3. Visual Studio creates the Form1 class. Change its StartPosition property to CenterScreen. In this sample, Form1 is the splash screen.
  4. Add a new class named SplashFormFactory with the following code:
namespace WindowsFormsApplication1
{
    using System.Threading;
    using System.Windows.Forms;

    public class SplashFormFactory
    {
        private Form splashForm;

        public void ShowSplashForm()
        {
            ThreadPool.QueueUserWorkItem(this.ShowSplashForm);
        }

        public void CloseSplashForm()
        {
            this.splashForm.Invoke(new MethodInvoker(this.Close));
        }

        private void Close()
        {
            this.splashForm.Close();
        }

        private void ShowSplashForm(object stateInfo)
        {
            this.splashForm = new Form1();
            Application.Run(this.splashForm);
        }
    }
}
  1. Modify the program.cs as follows:
namespace WindowsFormsApplication1
{
    using System;
    using System.Threading;
    using System.Windows.Forms;

    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            var splashFormFactory = new SplashFormFactory();
            splashFormFactory.ShowSplashForm();

            Thread.Sleep(1000);
            MessageBox.Show("Yes, I'm sure I'm doing something wrong here. But can you tell me exactly what it is?");
            splashFormFactory.CloseSplashForm();
        }
    }
}
  1. Press the F5 key. The message is displayed on top of the splash screen as expected when running with the Visual Studio.
  2. Now, double click the executable file in Windows Explorer. The message box is displayed behind the splash screen.

Thanks,


tetsu


Viewing all articles
Browse latest Browse all 12583

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>