What is the "right" way to bring a Windows Forms Application to the foreground?
I am writing a Windows Forms Application in C#. I need to be able to bring it to the foreground. After some Googling and experimentation, I have a working solution that looks pretty hacky.
I would like to know the elegant way to do this, if there is one. I need the app to restore and come to the foreground whether it was minimized, or not minimized but in background.
Current code looks like this:
WindowState = FormWindowState.Minimized;
WindowState = FormWindowState.Normal;
BringToFront();
Focus();
Solution 1:
Have you tried Form.Activate?
This code seems to do what you want, by restoring the form to normal size if minimized and then activating it to set the focus:
if (this.WindowState == FormWindowState.Minimized)
{
this.WindowState = FormWindowState.Normal;
}
this.Activate();
Warning: this is annoying! If it's just an app for your personal use, as you say, maybe you can live with it. :)
Solution 2:
Note. Below I have copied the most voted answer in a linked question closed as a duplicate to this one. That answer is the only pure C# answer I've found that solves this problem.
this.WindowState = FormWindowState.Minimized;
this.Show();
this.WindowState = FormWindowState.Normal;
It always brings the desired window to the front of all the others.