大家。 我遇到了这样的问题。在我的应用程序中,我通过ShowDialog方法从我的主窗体中显示第二个窗体。在这种形式中,我有一些文本框连接到数据库和一个连接按钮。如果用户单击X,则应用程序退出。但是如果用户单击“连接” - 我连接到DB并关闭我的第二个表单。为了捕获结束事件,我使用FormClosing方法,其中应用程序询问我是否要关闭应用程序,如果是,则退出。问题是,当我单击按钮时,FormClosing事件将触发并询问我是否要退出。怎么避免呢?我尝试使用发件人,但它不起作用。
这是我的代码:
private void Connect_Click(object sender, EventArgs e)
{
try
{
orcl.connect(userID.Text, Password.Text, comboTNS.Text);
if (orcl.ifHasRows("select dbclass from setupdbversion where dbclass='SECURITY' and rownum=1"))
{//my stuff
this.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
};
}
private void SecConnForm_FormClosing_1(object sender, FormClosingEventArgs e)
{
MessageBox.Show(sender.ToString());
if (e.CloseReason == CloseReason.UserClosing)
{
MessageBox.Show(sender.ToString());
if (string.Equals((sender as Form).Name, @"SecConnForm")) //it doesn't work as in any cases the sender is my form, not a button (when i click on button of course)
{
if (MessageBox.Show(this, "Really exit?", "Closing...",
MessageBoxButtons.OKCancel, MessageBoxIcon.Question)
== DialogResult.Cancel)
e.Cancel = true;
else
Application.Exit();
}
else
{
//other stuff goes..
}
}
}
答案 0 :(得分:2)
表单结束事件将在每次表单关闭时触发,无论是通过代码还是通过用户单击完成。
您需要的是类似的东西。
private boolean bFormCloseFlag = false;
private void Connect_Click(object sender, EventArgs e)
{
try
{
orcl.connect(userID.Text, Password.Text, comboTNS.Text);
if (orcl.ifHasRows("select dbclass from setupdbversion where dbclass='SECURITY' and rownum=1"))
{//my stuff
bFormCloseFlag = true;
this.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
};
}
private void SecConnForm_FormClosing_1(object sender, FormClosingEventArgs e)
{
if (bFormCloseFlag = false)
{
MessageBox.Show(sender.ToString());
if (e.CloseReason == CloseReason.UserClosing)
{
MessageBox.Show(sender.ToString());
if (string.Equals((sender as Form).Name, @"SecConnForm")) //it doesn't work as in any cases the sender is my form, not a button (when i click on button of course)
{
if (MessageBox.Show(this, "Really exit?", "Closing...",
MessageBoxButtons.OKCancel, MessageBoxIcon.Question)
== DialogResult.Cancel)
e.Cancel = true;
else
Application.Exit();
}
else
{
//other stuff goes..
}
}
}
}
此标志只会检查表单是否通过“X”按钮单击关闭,或者您的代码将其关闭。
答案 1 :(得分:0)
this.Close()触发关闭类型“UserClosing” 可能只是隐藏对话框而不是this.close()?