I have a C# Winforms application that spawns sub forms. All works well, but it draws the sub forms on top of the main form. I want to force the main form to be on top of the sub forms when any part of it is clicked.
I have tried:
this.Refresh();
this.Activate();
this.BringToFront();
None of these have the desired effect.
I have a C# Winforms application that spawns sub forms. All works well, but it draws the sub forms on top of the main form. I want to force the main form to be on top of the sub forms when any part of it is clicked.
I have tried:
this.Refresh();
this.Activate();
this.BringToFront();
None of these have the desired effect.
Share Improve this question edited Apr 1 at 4:54 marc_s 756k184 gold badges1.4k silver badges1.5k bronze badges asked Mar 31 at 22:36 Mark AinsworthMark Ainsworth 8698 silver badges25 bronze badges 1- The code you use to "spawn" your sub form is relevant. You should show it as part of your question. – Wyck Commented 6 hours ago
2 Answers
Reset to default 3Make sure you're doing:
form.Show();
instead of:
form.Show(this);
If you use the second overload to show your sub forms you'll make them child forms which will prevent them from being drawn behind their parent (aka owner).
Here's some sample code showing this behavior:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Size = new Size(500, 500);
this.Controls.Add(new Label() { Text = "Main Form", Width = 100 });
var form1 = new Form();
form1.Controls.Add(new Label() { Text = "This sub form is always on top of Main Form", Width = 250 });
form1.Show(this);
form1.Location = new Point(this.Location.X + 250, this.Location.Y);
var form2 = new Form();
form2.Controls.Add(new Label() { Text = "This sub form can be behind Main Form", Width = 250 });
form2.Show();
form2.Location = new Point(this.Location.X, this.Location.Y);
this.Location = new Point(this.Location.X, this.Location.Y + 100);
}
}
This is also mentioned in the docs:
When a form is owned by another form, it is closed or hidden with the owner form. For example, consider a form named Form2 that is owned by a form named Form1. If Form1 is closed or minimized, Form2 is also closed or hidden. Owned forms are also never displayed behind their owner form. You can use owned forms for windows such as find and replace windows, which should not disappear when the owner form is selected.
Set the TopMost
property to true
in the form's constructor or Load
event:
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
this.TopMost = true;
}
}
If you need to force it on top continuously (in case another app tries to take focus), you can use a timer to periodically ensure it stays on top:
private void Form1_Load(object sender, EventArgs e)
{
Timer timer = new Timer();
timer.Interval = 1000; // 1 second
timer.Tick += (s, ev) => this.TopMost = true;
timer.Start();
}