这是我上面提到的示例。
此代码位于 TaskbarUtility 中,整个应用程序中的所有事件都通过这里创建新的表单。
我不确定这是否是执行此类操作的“正确”方式,并且我不打算进行线程劫持,但我想我不妨分享一下。:)
List<CommonFormBase> activeWindows = new List<CommonFormBase>();
public void LaunchApplication(ApplicationWindowType formTypeToLaunch)
{
CommonFormBase tempForm;
switch (formTypeToLaunch)
{
//implement code to create a new form here
}
activeWindows.Add(tempForm);
tempForm.Name = "UniqueName:" + System.DateTime.Now;
tempForm.FormClosed += new FormClosedEventHandler(tempForm_FormClosed);
tempForm.Show();
}
void tempForm_FormClosed(object sender, FormClosedEventArgs e)
{
if (sender is CommonFormBase)
{
//Get the index of the selected form
int index = -1;
for (int i = 0; i <= this.activeWindows.Count - 1; i++)
{
if (this.activeWindows[i].Name == ((Form)sender).Name)
index = i;
}
//Remove the selected form from the list
if (index >= 0)
activeWindows.RemoveAt(index);
//Close the TaskbarUtility if no remaining windows
// and user choose to exit when none remain
if (this.activeWindows.Count == 0 && CloseWhenNoWindowsRemain)
{
this.Close();
}
}
}
希望这是有道理的。
假设并非所有用户都希望应用程序一直运行,因此当他们启用该选项时,这将关闭整个程序。