Search code examples
c#winformsmultithreadingformstopmost

TopMost form in a thread?


I am using the following code to open a form in a new thread:

private void button1_Click(object sender, EventArgs e)
{

    Thread thread = new Thread(ThreadProc);
    thread.Start();
}


public void ThreadProc()
{

    Form form = new Form();
    form.TopMost = true;
    form.ShowDialog();
}

But the newly created form isn't TopMost even though I set it to true.

How can I make a form in a thread TopMost ?


Solution

  • Usually you don't need another thread, you open the form as usual in modal or non modal mode, if the form needs to do a heavy process then you do the process inside a thread.

    Specific to your question one option is to run the form from an Application.Run as described here.

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            Thread thread = new Thread(ThreadProc);
            thread.Start();
        }
    
    
        public void ThreadProc()
        {
            using (Form1 _form = new Form1())
            {
                _form.TopMost = true;
                Application.Run(_form);
            }
        }
    }
    

    That will launch a new thread with its own message pump and will keep it as a TopMost form.