如何将一个Windows窗体置于顶层?

5

我正在使用C#开发一个Windows窗体应用程序。当特定类型的外部事件发生时(例如,当鼠标位置y=0时,我想在窗体上写上“鼠标在上方线上”),该应用程序会在窗体上显示一些文本。当事件发生时,我需要将该窗体置于所有其他窗口之上。


我已经编辑了你的问题,试图使其更清晰,但仍然不清楚,你所说的“鼠标位置y=0”是什么意思。 - Sayse
你需要使用mdiparent和mdichild来区分不同的类,并将它们显示在前面,激活或执行其他操作。 - Sakthivel
@Sayse:这并不重要,我只是想举个事件的例子。 - Ahmad Sadigh
3个回答

5

在您的表单类中使用以下内容:

public void BringToTop()
{
    //Checks if the method is called from UI thread or not
    if (this.InvokeRequired)
    {
        this.Invoke(new Action(BringToTop));
    }
    else
    {
        if (this.WindowState == FormWindowState.Minimized)
        {
            this.WindowState = FormWindowState.Normal;
        }
        //Keeps the current topmost status of form
        bool top = TopMost;
        //Brings the form to top
        TopMost = true;
        //Set form's topmost status back to whatever it was
        TopMost = top;
    }
}

我进行了测试,它确实有效。谢谢。 - Ahmad Sadigh
1
我得到了另一个人的帮助,现在我只是把它传递给你。 - John Steven

2

0

尝试使用这个

yourForm.TopMost = true;

你将如何从外部事件中将它设置为 true? - Sayse
1
如果窗口被最小化了,它就无法工作。 - cyberj0g
1
它给了我运行时错误。从异常消息来看,我认为我不能从另一个线程更改值。 - Ahmad Sadigh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接