我有一個MDIPrent窗體,這是我的主要形式。現在我通過單擊LogOut MenuStrip註銷Main_Form。在我的代碼中,我阻止了重複的實例。但是我得到這個錯誤。我搜索了很多東西,嘗試了很多東西,但錯誤並沒有消失。 下面是Program.cs的文件代碼:在單個線程上啓動第二個消息循環不是有效的操作。使用Form.ShowDialog代替
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。某處我有了使用上下文的想法。
創建新的進程,而不是Application.Run(背景); 這不是一個很好的解決方案,但我會寫一個很好的,如果你告訴我你爲什麼要做Application.Run()在第一個 –
我應該創建進程logOut或而不是Application.Run()?我通常做Application.Run()來啓動應用程序。 – DhavalR
你想要達到 –