1

我有一个文本框TBEH事件焦点/离开的处理程序。

另外,我有一个按钮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();
}
4

2 回答 2

1

保留一个指示是否发出退出请求的指示符。

private bool _isQuitRequested = false;

在BT点击事件中添加

private void BT_Click(object sender, EventArgs e) // --- PROGRAM END ---
{
    _isQuitRequested = true;
    Dispose();
}

在事件处理程序的开头EH添加

if (_isQuitRequested) return;

不要忘记改_isQuitRequest回false inTB_TextChanged

于 2013-09-12T20:47:30.563 回答
0

您可以尝试创建一个全局字段来存储程序退出的权限,如下所示;

bool Quit=false;

现在,当您完成一些检查是否退出程序时,您可以将此变量设置为truefalse以防留下一些东西。从现在开始,每当BT_Click触发事件(退出事件)时,将此变量设置为 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运行中的逻辑,设置QuitfalseTextChangedEvent像这样;

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;
}
于 2013-09-12T21:10:26.713 回答