-1

I have a C# WinForms application that utilises a ControllerBase to handle interaction with a Google Chrome extension.

When a result is received, I would like to display a Form. However, even though I set the Form to be TopMost, along with other variations such as BringToFront(), the Form non-deterministically either displays 'TopMost', and is displayed to the user as expected, or sits in the taskbar and the user then has to click the opened Form in the taskbar to then bring it to front and focus. I cannot describe the behaviour better than sometimes the Form shows as expected (i.e. top most), and other times it does not (i.e. it opens but sits in the taskbar).

How can I ensure the Form always displays top most to the user?

For additional context, there is another Form, we'll call MainForm that is also running and contains the ControllerBase logic. The MainForm is not always necessarily in view or focus, but is running.

[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(); 
    }
}
TEK
  • 1,265
  • 1
  • 15
  • 30

1 Answers1

0

I ended up following a similar solution as seen at https://stackoverflow.com/a/60046440/2215712

I put all the GUI-related logic (the Form I wanted to show) in a method within the MainForm. The Form now always displays and is top most.

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