开发者

How to know if the Form App open or not c#

Does anyone know how can I know if the Windows Form Application (C#) is open or that the client closed it?

(In my App I have a Windows Form Application (Form1) that allow the user to open another Forms (Form2). I want to know if the For开发者_开发技巧m2 is open or close.)

I need to know that because I run the Form2 from a thread, and I want to make the thread runnig until the user close Form2.

Many thanks!


You can check if a form of a given type is open in your application like this (using LINQ):

if (Application.OpenForms.OfType<Form2>().Count() > 0)
{
    // there is an instance of Form2 loaded
}


You need to elaborate on your question a bit more. Are you talking about monitoring the application from another application? Or that one form needs to know if another one is open? Or a form needs to know when another form closes?

There are a couple of ways to monitor forms closing within the same application.

Calling ShowDialog() on your form instead of Show() will ensure that code following the ShowDialog() call doesn't get executed until the user closes the form.

The Form class has a Visible property, which returns true/false depending on whether the form is visible or not.

As for the application itself, there is an ApplicationExit event on the static Application class which gets called just before the application closes so you could listen to that event if, for example, you need to perform some clean-up on exit.


If you want to run only single instance of application, check this link.
There you will also see how to check whether a process is still active.


If you mean MDI application with its child forms:

private Dictionary<Type, Form> SingleInstanceForms = new Dictionary<Type, Form>();

public Form ActivateForm<T>() where T : Form, new()
{
    Cursor.Current = Cursors.WaitCursor;

    if (!this.SingleInstanceForms.ContainsKey(typeof(T)))
    {
        T newForm = new T();
        //setup child
        newForm.MdiParent = this;
        newForm.WindowState = FormWindowState.Maximized;
        //newForm.Icon = Icon;

        newForm.FormClosed += new FormClosedEventHandler(delegate(object sender, FormClosedEventArgs e)
        {
            this.SingleInstanceForms.Remove(sender.GetType());
        });

        this.SingleInstanceForms.Add(typeof(T), newForm);

        newForm.Show();
        this.Refresh();
    }

    Form formToActivate = this.SingleInstanceForms[typeof(T)];
    formToActivate.Activate();

    Cursor.Current = Cursors.Default;

    return formToActivate;
}

this will create the form child if hasn't been created yet and activate it if it has been created.

sample: ActivateForm<dlgChildOne>();

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜