我有一个文本框TB
和一个处理程序EH
用于事件焦点/离开。
另外,我有一个按钮BT
在点击时退出程序,只有dispose();
如果我在TB
框中没有正确的数据,则会触发焦点离开事件处理程序来检查数据,它会向我发出警告并将焦点返回到TB
。
但是,如果我想在TB
有焦点的情况下退出该计划并点击BT
,则会再次触发EH
并将焦点返回到TB
和程序不会放弃。
我该如何解决这个问题?这是代码:
public Form1()
{
InitializeComponent();
}
private void EH(object sender, EventArgs e) // event handler EH
{
double temp;
if (TB.Text == "")
{
MessageBox.Show("Must enter a valid distance for d1!\r\n" +
"The valid range is ( 10,32 )",
"Wake up!", MessageBoxButtons.OK, MessageBoxIcon.Error);
TB.Focus();
return;
}
else
try
{
temp = Convert.ToDouble(TB.Text);
if (temp < 10 || temp > 32)
{
MessageBox.Show("Invalid distance for d1!\r\n" +
"The valid range is ( 10,32 )",
"Again! Wake up!", MessageBoxButtons.OK, MessageBoxIcon.Error);
TB.Text = "";
TB.Focus();
return;
}
minh1 = 1 / 8 * temp; // sets minimum h1
if (minh1 < 10)
minh1 = 10;
}
catch (Exception) // can't convert
{
MessageBox.Show("Invalid numeric entry!\r\n" +
"Please enter a valid number!",
"Hey! Wake up!", MessageBoxButtons.OK, MessageBoxIcon.Error);
TB.Text = "";
TB.Focus();
}
}
private void TB_TextChanged(object sender, EventArgs e) // change text in TB
{
if (TB.Text == "")
btgo.Enabled = false;
else
btgo.Enabled = true;
}
private void btgo_Click(object sender, EventArgs e) // Execute!
{
say.Text = "Minimum height h1 has been calculated to be " +
string.Format("{0:#0.00}", minh1) + " Fts";
BT.Focus();
}
private void BT_Click(object sender, EventArgs e) // --- PROGRAM END ---
{
Dispose();
}
答案 0 :(得分:1)
保留一个指示器,说明是否已提出退出请求。
private bool _isQuitRequested = false;
在BT点击事件中添加
private void BT_Click(object sender, EventArgs e) // --- PROGRAM END ---
{
_isQuitRequested = true;
Dispose();
}
在事件处理程序EH
的开头添加
if (_isQuitRequested) return;
不要忘记在_isQuitRequest
TB_TextChanged
更改回false
答案 1 :(得分:0)
您可以尝试创建一个全局字段来存储程序退出的权限,如下所示;
bool Quit=false;
现在,当您完成一些检查是否要退出程序时,您可以将此变量设置为true
或false
,以防遗留任何内容。从BT_Click
开始触发事件(Exit事件)将此变量设置为true,如下所示;
private void BT_Click(object sender, EventArgs e) //--- PROGRAM END ---
{
Quit = true;//Flag to exit the program.
Dispose();
}
如果你没有这个,请在EH
;
private void EH(object sender, EventArgs e) // event handler EH
{
if(Quit)//If Quit is true,means exit the program.
{
return;//No processing,just return.
}
//Run regular logic,if the function doesn't need to return.
}
但要确保EH
中的逻辑运行,请在Quit
中将false
设置为TextChangedEvent
,就像这样;
private void TB_TextChanged(object sender, EventArgs e) // change text in TB
{
Quit=false;//Set this to false to make sure `EH` event's code is executed.
if (TB.Text == "")
btgo.Enabled = false;
else
btgo.Enabled = true;
}