当用户按下X按钮时,如何从第二个表单中完全退出C#应用程序?
到目前为止,这是我的代码:
Form1.cs的
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 1)
{
String cellValue;
cellValue = dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString();
var form2 = new Form2(cellValue);
this.Hide();
form2.Show();
}
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
if (e.CloseReason == CloseReason.WindowsShutDown) return;
switch (MessageBox.Show(this, "Are you sure you want to exit?", "", MessageBoxButtons.YesNo))
{
case DialogResult.No:
e.Cancel = true;
break;
default:
break;
}
}
Form2.cs
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
if (e.CloseReason == CloseReason.WindowsShutDown) return;
switch (MessageBox.Show(this, "Are you sure you want to exit?", "", MessageBoxButtons.YesNo))
{
case DialogResult.No:
e.Cancel = true;
break;
default:
break;
}
}
答案 0 :(得分:3)
protected override void OnFormClosing(FormClosingEventArgs e)
{
DialogResult dgResult = MessageBox.Show(this, "Are you sure you want to exit?", "", MessageBoxButtons.YesNo);
if(dgResult==DialogResult.No)
e.Cancel = true;
else
//here you can use Environment.Exit which is not recomended because it does not generate a message loop to notify others form
Environment.Exit(1);
//or you can use
//Application.Exit();
}
答案 1 :(得分:2)
基于评论,这样的声音是一个可行的解决方案:
private bool userRequestedExit = false;
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
if (this.userRequestedExit) {
return;
}
if (e.CloseReason == CloseReason.WindowsShutDown) return;
switch (MessageBox.Show(this, "Are you sure you want to exit?", "", MessageBoxButtons.YesNo))
{
case DialogResult.No:
e.Cancel = true;
break;
default:
this.userRequestedExit = true;
Application.Exit();
break;
}
}