winforms 确保通过ControllerBase创建表单时始终显示在最上方

ki1q1bka  于 8个月前  发布在  其他
关注(0)|答案(1)|浏览(62)

我有一个C# WinForms应用程序,它利用ControllerBase来处理与Google Chrome扩展的交互。
当收到结果时,我想显示一个Form。然而,即使我将Form设置为TopMost,沿着的还有其他变体,如BringToFront()Form也不确定地显示“TopMost”,并按预期显示给用户,或者位于屏幕中,用户必须单击屏幕中打开的Form,然后将其置于前面并聚焦。我不能描述的行为比有时更好的Form显示预期(即。最上面的),而其他时候它不这样做(即它打开但位于任务栏中)。
如何确保Form始终显示在用户的最上方?
对于其他上下文,还有另一个Form,我们将其称为MainForm,它也在运行并包含ControllerBase逻辑。MainForm不一定总是在视图或焦点中,但它正在运行。

[Route("api/example")]
[ApiController]
public class MinimalExampleController : ControllerBase
{
    [Route("sendcontent")]
    [HttpPost]
    public IActionResult OnResultReceived()
    {
        Form form = new Form();
        form.TopMost = true;
        form.BringToFront();
        form.Focus();
        
        form.ShowDialog();
        
        return Ok(); 
    }
}
ewm0tg9j

ewm0tg9j1#

我最终采用了与https://stackoverflow.com/a/60046440/2215712类似的解决方案
我将所有与GUI相关的逻辑(我想展示的Form)放在MainForm中的一个方法中。Form现在始终显示并位于最顶部。

public IActionResult OnResultReceived()
{
     Program.MainForm.Invoke(new Action(() =>
     {
           //ShowForm is a static method that creates and shows the Form      
           MainForm.ShowForm();
     }));
     return Ok();
}

相关问题