我有一份 MDIPrent 表格,这是我的主要表格。现在,我通过单击 LogOut MenuStrip 退出表单 Main_Form。在我的代码中,我防止了重复实例。但我得到这个错误。我用谷歌搜索了很多,尝试了很多东西,但错误并没有消失。以下是 Program.cs 文件的代码:
using System.Diagnostics;
static class Program
{
[STAThread]
static void Main()
{
LoggedInUser = string.Empty;
loginSuccess = false;
String thisprocessname = Process.GetCurrentProcess().ProcessName;
if (Process.GetProcesses().Count(p => p.ProcessName == thisprocessname) > 1)
return;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
MyApplicationContext context = new MyApplicationContext();
Application.Run(context);
}
public class MyApplicationContext : ApplicationContext
{
private Login_Form lgFrm = new Login_Form();
public MyApplicationContext()
{
try
{
lgFrm.ShowDialog();
if (lgFrm.LogonSuccessful)
{
////lgFrm.Close();
lgFrm.Dispose();
FormCollection frm = Application.OpenForms;
try
{
foreach (Form fc in frm)
fc.Close();
}
catch (Exception ex){}
Application.Run(new Main_Form());
}
}
catch (Exception ex){}
}
}
}
下面是 Login_Form 的代码
public bool LogonSuccessful
{
get
{
return Program.loginSuccess;
}
set
{
Program.loginSuccess = value;
}
}
private void BtnEnter_Click(object sender, EventArgs e)
{
Login_Form lgn = new Login_Form();
Program.loginSuccess = true;
this.Hide();
Program.LoggedInUser = TxtBxUserName.Text;
}
下面是 Main_Form
private void LogOutMenuItem_Click(object sender, EventArgs e)
{
Login_Form lgFrm = new Login_Form();
lgFrm.LogonSuccessful = false;
Program.loggedOut = true;
Program.LoggedInUser = string.Empty;
this.Close();
////FormCollection frm = Application.OpenForms;
////foreach (Form fc in frm)
////{
//// MessageBox.Show(fc.ToString());
////}
Program.MyApplicationContext context = new Program.MyApplicationContext();
Application.Run(context);
}
我使用了上下文,因为我想让 Main_Form 成为应用程序的唯一 OpenForm。在某个地方,我有了使用上下文的想法。