简体   繁体   中英

How to bring a win form to front?

I have a winform that drives me crazy... When I open it, it opens and goes behind the main form from which I open it. I tried calling: BringToFront(), Focus(), Activacte() and still nothing.... Here is my code:

MyForm frm = new MyForm();
frm.WindowState = FormWindowState.Maximized;
frm.StartPosition = FormStartPosition.CenterParent;
frm.Show();
frm.BringToFront();
frm.Activate();

I know that the main form has the TopMost property set to true, but I also have this code that works just fine:

Form frmLog = new Form();
LogViewer logControl = new LogViewer();
frmLog.Controls.Add(logControl);
logControl.Dock = DockStyle.Fill;
frmLog.WindowState = FormWindowState.Maximized;
frmLog.StartPosition = FormStartPosition.CenterParent;
frmLog.Text = "Log Viewer";
frmLog.Show();

So that is way it drives me crazy...

You have to set your main form as owner for frm by using Form.Show(IWin32Window) method.

So your code should look like

frm.Show(this);

You have to pass the instance of the main form to the Show method of the form you want to show.

MyForm frm = new MyForm();
frm.Show(this);

Of course this works if you are instanciating the second form inside the main form class (so you can use the this keyword.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM