如何检查窗口窗体是否已经打开,如果已经打开,如何关闭窗口窗体?

我有一个表格 “ fm”,这是一个简单的信息窗口,打开每10分钟(fm.Show();)。

如何我可以使每10分钟它将检查表格 “ fm”是打开的,如果它是打开它关闭它,并再次打开它!

现在,始终使用 form fm = new form();创建表单 fm
因此,当我尝试检查表单是否打开时,它总是为 false,并且即使之前有一个表单,也会打开一个新窗口!

我需要有一个工具,给它一个独特的身份,然后检查这个形式与独特的身份是否打开!

我不想只是更新表单(fm)上的数据,因为我有一个复杂的按钮信息。

表单名称为 "UpdateWindow"

谢谢

266800 次浏览

maybe this helps:

FormCollection fc = Application.OpenForms;


foreach (Form frm in fc)
{
//iterate through
if (frm.Name == "YourFormName")
{
bFormNameOpen = true;
}
}

Some code in the foreach to detect the specific form and it could be done. Untested though.

Found on http://bytes.com/topic/c-sharp/answers/591308-iterating-all-open-forms

I'm not sure that I understand the statement. Hope this helps. If you want to operate with only one instance of this form you should prevent Form.Dispose call on user close. In order to do this, you can handle child form's Closing event.

private void ChildForm_FormClosing(object sender, FormClosingEventArgs e)
{
this.Hide();
e.Cancel = true;
}

And then you don't need to create new instances of frm. Just call Show method on the instance.

You can check Form.Visible property to check if the form open at the moment.

private ChildForm form = new ChildForm();


private void ReopenChildForm()
{
if(form.Visible)
{
form.Hide();
}
//Update form information
form.Show();
}

Actually, I still don't understand why don't you just update the data on the form.

Try to wire below,

private void frmMyForm_Deactivate(object sender, EventArgs e)
{
// Raise your flag here.
}

By wiring above event, it will tell you whenever the form is minimized, partially/totally hided by another form.

This is what I used to close all open forms (except for the main form)

    private void CloseOpenForms()
{


// Close all open forms - except for the main form.  (This is usually OpenForms[0].
// Closing a form decrmements the OpenForms count
while (Application.OpenForms.Count > 1)
{
Application.OpenForms[Application.OpenForms.Count-1].Close();
}
}

Suppose if we are calling a form from a menu click on MDI form, then we need to create the instance declaration of that form at top level like this:

Form1 fm = null;

Then we need to define the menu click event to call the Form1 as follows:

private void form1ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (fm == null|| fm.Text=="")
{
fm = new Form1();
fm.MdiParent = this;
fm.Dock = DockStyle.Fill;
fm.Show();
}
else if (CheckOpened(fm.Text))
{
fm.WindowState = FormWindowState.Normal;
fm.Dock = DockStyle.Fill;
fm.Show();
fm.Focus();
}
}

The CheckOpened defined to check the Form1 is already opened or not:

private bool CheckOpened(string name)
{
FormCollection fc = Application.OpenForms;


foreach (Form frm in fc)
{
if (frm.Text == name)
{
return true;
}
}
return false;
}

Hope this will solve the issues on creating multiple instance of a form also getting focus to the Form1 on menu click if it is already opened or minimized.

Funny, I had to add to this thread.

1) Add a global var on form.show() and clear out the var on form.close()

2) On the parent form add a timer. Keep the child form open and update your data every 10 min.

3) put timer on the child form to go update data on itself.

if( ((Form1)Application.OpenForms["Form1"]).Visible == true)
//form is visible
else
//form is invisible

where Form1 is the name of your form.

Form1 fc = Application.OpenForms["Form1 "] != null ? (Form1 ) Application.OpenForms["Form1 "] : null;
if (fc != null)
{
fc.Close();
}

It will close the form1 you can open that form again if you want it using :

Form1 frm = New Form1();
frm.show();

I know I am late... But for those who are curious... This is another way

if (Application.OpenForms.OfType<UpdateWindow>().Count() == 1)
Application.OpenForms.OfType<UpdateWindow>().First().Close();


UpdateWindow frm = new UpdateWindow()
frm.Show();

* Hope This will work for u

System.Windows.Forms.Form f1 = System.Windows.Forms.Application.OpenForms["Order"];
if(((Order)f1)!=null)
{
//open Form
}
else
{
//not open
}

try this

 bool IsOpen = false;
foreach (Form f in Application.OpenForms)
{
if (f.Text == "Form2")
{
IsOpen = true;
f.Focus();
break;
}
}


if (IsOpen == false)
{
Form2 f2 = new Form2();
f2.MdiParent = this;
f2.Show();
}

Try this, it will work :

//inside main class
Form1 Fm1 = new Form1();<br>


//in button click
if (Fm1.IsDisposed)
{
Fm1 = new Form();
}
Fm1.Show();
Fm1.BringToFront();
Fm1.Activate();
 private static Form IsFormAlreadyOpen(Type formType)
{
return Application.OpenForms.Cast<Form>().FirstOrDefault(openForm => openForm.GetType() == formType);
}

Form only once

If your goal is to diallow multiple instaces of a form, consider following ...

public class MyForm : Form
{
private static MyForm alreadyOpened = null;


public MyForm()
{
// If the form already exists, and has not been closed
if (alreadyOpened != null && !alreadyOpened.IsDisposed)
{
alreadyOpened.Focus();            // Bring the old one to top
Shown += (s, e) => this.Close();  // and destroy the new one.
return;
}


// Otherwise store this one as reference
alreadyOpened = this;


// Initialization
InitializeComponent();
}
}

In addition, may be this will help


class Helper
{
public void disableMultiWindow(Form MdiParent, string formName)
{
FormCollection fc = Application.OpenForms;
try
{
foreach (Form form in Application.OpenForms)
{
if (form.Name == formName)
{
form.BringToFront();
return;
}
}


Assembly thisAssembly = Assembly.GetExecutingAssembly();
Type typeToCreate = thisAssembly.GetTypes().Where(t => t.Name == formName).First();
Form myProgram = (Form)Activator.CreateInstance(typeToCreate);
myProgram.MdiParent = MdiParent;
myProgram.Show();
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
}

Form user_rpt = Application.OpenForms["frmUesr_reports"];
if (user_rpt == null)
{
/// Do Something here
}

Try This This is the short idea to check Form open or not open

In my app I had a mainmenu form that had buttons to navigate to an assortment of other forms (aka sub-forms). I wanted only one instance of each sub-form to be running at a time. Plus I wanted to ensure if a user attempted to launch a sub-form already in existence, that the sub-form would be forced to show "front&center" if minimized or behind other app windows. Using the currently most upvoted answers, I refactored their answers into this:

private void btnOpenSubForm_Click(object sender, EventArgs e)
{


Form fsf = Application.OpenForms["formSubForm"];


if (fsf != null)
{
fsf.WindowState = FormWindowState.Normal;
fsf.Show();
fsf.TopMost = true;
}
else
{
Form formSubForm = new FormSubForm();
formSubForm.Show();
formSubForm.TopMost = true;
}
}
if (Application.OpenForms["Form_NAME"] == null)
{
new Form_NAME().Show();
}

If the form instance is not open it will enter the IF loop.

try this MDICHILD function

public void mdiChild(Form mdiParent, Form mdiChild)
{
foreach (Form frm in mdiParent.MdiChildren)
{
// check if name equals
if (frm.Name == mdiChild.Name)
{
//close if found


frm.Close();


return;
}
}


mdiChild.MdiParent = mdiParent;


mdiChild.Show();


mdiChild.BringToFront();
}

This worked form me:

public void DetectOpenedForm()
{
FormCollection AllForms = Application.OpenForms;
Boolean FormOpen = false;
Form OpenedForm = new Form();
foreach (Form form in AllForms)
{
if (form.Name == "YourFormName")
{
OpenedForm = form;
FormOpen = true;
}
}
if (FormOpen == true)
{
OpenedForm.Close();
}
}

I think my method is the simplest.

    Form2 form2 = null;
private void SwitchFormShowClose_Click(object sender, EventArgs e)
{
if(form2 == null){
form2 = new Form2();
form2.Show();
}
else{
form2.Close();
form2 = null;
}
}

The below actually works very well.

private void networkInformationToolStripMenuItem_Click(object sender, EventArgs e)
{
var _open = false;
FormCollection fc = Application.OpenForms;
foreach (Form frm in fc)
{
if (frm.Name == "FormBrowseNetworkInformation")
{
_open = true;
frm.Select();
break;
}
}
if (_open == false)
{
var formBrowseNetworkInformation = new FormBrowseNetworkInformation();
formBrowseNetworkInformation.Show();
}
}
Form fc = Application.OpenForms["UpdateWindow"];


if (fc != null)
fc.Close();


fc.Show();

this will word definitely. i use this function for myself as well.

  public static bool isFormOpen(Form formm)
{


foreach (Form OpenForm in Application.OpenForms)
{
if (OpenForm.Name == formm.Name)
{
return true;
}
}


return false;
}

I've tweaked an earlier post I made. This work flawlessly without having to iterate though all open forms.

        Form fc = Application.OpenForms["FormBrowse"];
if (fc != null)
{
fc.Select();
}
else
{
var formBrowse = new FormBrowse();
formBrowse.Show();
}

try this , no need to iterate through the forms :

if(Application.OpenForms["<your_form_name>"] != null){


//Your form is already open


}
else {


//Your form isn't open


}

This works if you want to Check if the Second Form is already Open and avoidt opening it again on buttong Click.

 int formcheck = 0;
private void button_click()
{
Form2Name myForm2 = new Form2Name();
if(formcheck == 0)
{
myForm2.Show(); //Open Form2 only if its not active and formcheck == 0
// Do Somethin


formcheck = 1; //Set it to 1 indicating that Form2 have been opened
{
{

You can use ShowDialog() instead of using Show()

Something like this:

var newView = (viewForm)Program.ServiceProvider.GetService(typeof(viewForm));
newView.ShowDialog();

For example:

private bool CheckOpened<T>() where T : Form
{
bool result = false;
FormCollection fs = Application.OpenForms;


foreach (var f in fs)
{
if (f is T)
{
result = true;
break;
}
}


return result;
}


private void ShowDashboard()
{
if (!CheckOpened<FormMain>())
{
var fMain = new FormMain();
fMain.Show();
}
}