简体   繁体   中英

How can I control threaded windows in C#

I have a C# application which runs as a context menu in the system tray. One of the options will display a 'system information' box and at the moment I'm opening this window in another thread (on click event) like this...

void menu_SystemInformation_Click(object sender, EventArgs e)
{
    System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(menu_Systeminformation_Thread));
t.Start();
}
void menu_Systeminformation_Thread()
{
    Application.Run(new SystemInformation());
}

I have two questions about this...

  1. How can I make sure that only one instance of this form is opened when the option is selected.
  2. How can I automatically close this form (if it's open) when the application closes.

Any help is appreciated. I've only been doing C# for a few weeks, so go easy on me! Cheers,

1.How can I make sure that only one instance of this form is opened when the option is selected.

Programming. Have a central location, check whether you already have an open window. There is no automatism for that, but it is trivial to do.

2.How can I automatically close this form (if it's open) when the application closes.

You dont do anything. THe process closes, all windows get closed anyway. All open OS resources are rleased, including files etc.

I'd like to add to TomTom answer the following:

How can I make sure that only one instance of this form is opened when the option is selected.

I would implement the Singleton pattern to achieve it.

  1. If you mean one instance of the application - you can use named Mutex
  2. If you mean single instance of a concrete Form object - there are many different cases. As a straightforward solution - singleton. Basically declare static bool variable like static bool isInstanceCreated and check it before creating a new instance

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