C#.Net 判断窗体是否创建,如果已创建,激活窗体。
private Form2 frm2; private void button1_Click(object sender, EventArgs e) { if (frm2 == null) { frm2 = new Form2(); frm2.StartPosition = FormStartPosition.CenterScreen; frm2.Show(); } else { if (frm2.IsDisposed) { // 判断窗体是否关闭 关键代码 frm2 = new Form2(); frm2.StartPosition = FormStartPosition.CenterScreen; frm2.Show(); } else { frm2.WindowState = FormWindowState.Normal; // 窗体默认大小 frm2.Activate(); // 激活窗体 } } }
bool isFormOpen = false; private void button2_Click(object sender, EventArgs e) { foreach( Form frm in Application.OpenForms) { // 关键代码 if (frm is Form2) { // 如果此窗口已打开,则激活; frm.Activate(); frm.WindowState = FormWindowState.Normal; isFormOpen = true; break; } } if (!isFormOpen) { Form2 frm2 = new Form2(); frm2.Show(); } }
参考:
1.link-01。