Reputation: 2230
I have an .NET 4 WinForm application. I have a button on the main form that opens a child form. The child form has focus. While the child form is open, if I click on the main form, the main form receives focus, but the child form remains on top of the main form.
How can I make the main form come to the front, even if the child form is open?
Here is my sample code for the two forms:
using System;
using System.Windows.Forms;
namespace WinTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var form = new Form2();
form.Show(this);
}
}
}
using System.Windows.Forms;
namespace WinTest
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
}
}
Based on Kumar's answer below, I updated my main form as follows:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace WinTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
_FormList = new List<Form>();
}
private List<Form> _FormList;
private void button1_Click(object sender, EventArgs e)
{
var form = new Form2();
form.FormClosed += Form_FormClosed;
_FormList.Add(form);
form.Show();
}
private void Form_FormClosed(object sender, FormClosedEventArgs e)
{
_FormList.Remove((Form)sender);
}
private void Form1_Resize(object sender, EventArgs e)
{
foreach (var form in _FormList)
{
form.Visible = WindowState != FormWindowState.Minimized;
}
}
}
}
This now works as expected.
Upvotes: 2
Views: 4515
Reputation: 1015
As below
Form frm = null
private void button1_Click(object sender, EventArgs e)
{
frm = new Form2();
frm.Show();
}
// Minimize issue is handled
private void Form1_Resize(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)
{
frm.WindowState = this.WindowState;
}
}
Upvotes: 1
Reputation: 8564
Try removing the "this", and instead pass a null to the Show
method.
Upvotes: 0
Reputation: 518
Do this
form.Show();
instead of
form.Show(this);
The parameter set the parent of the form to be show. A parent form will be under his child form.
Upvotes: 7