简体   繁体   English

线程中的TopMost表单?

[英]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. 但是,即使我将其设置为true,新创建的表单也不是TopMost。

How can I make a form in a thread TopMost ? 如何在线程TopMost中创建表单?

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 . 具体到你的问题一个选项是描述从Application.Run运行的形式在这里

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. 这将启动一个带有自己的消息泵的新线程,并将其保留为TopMost表单。

Just ran into this problem myself. 我自己遇到了这个问题。 It seems that if the form has an Owner , then TopMost works as expected. 似乎如果表单有一个Owner ,那么TopMost按预期工作。 If the owning form was created on another thread, though, it's a little tricky to set . 但是,如果拥有的表单是在另一个线程上创建的,那么设置起来有点棘手 Here's what I used: 这是我用过的东西:

var form = new Form();

form.Shown += (sender, e) => {
    Control.CheckForIllegalCrossThreadCalls = false;
    form.Owner = /* Owning form here */;
    form.CenterToParent();      // Not necessary
    Control.CheckForIllegalCrossThreadCalls = true;

    form.TopMost = true;        // Works now!
};

Application.Run(form);

Instead of calling ShowDialog directly, try using this.Invoke to gain ownership of the form. 不要直接调用ShowDialog,而是尝试使用this.Invoke获取表单的所有权。

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;
    this.Invoke((Action)delegate() { form.ShowDialog(); });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM