C#停止,直到按下按钮

本文关键字:按钮 停止 | 更新日期: 2023-09-27 18:21:24

我正在c#中构建一个计算器。我想停止计算器并发出错误声音,直到按下清除按钮。就像计算平方根时,数字是-ve。

这是计算平方根的部分

 private void buttonSquareRoot_Click(object sender, EventArgs e)
    {
        num1 = double.Parse(textBox1.Text);
        if (num1 < 0.0)
        {
            textBox1.Text = "Invalid Input";
        }
        else
        {
            result = Math.Sqrt(double.Parse(textBox1.Text));
            textBox1.Text = Convert.ToString(result);
        }
    }

在错误消息后,我希望程序停止,直到点击清除按钮。我已经弄清楚了这个按钮。

 private void buttonClear_Click(object sender, EventArgs e)
    {
        textBox1.Text = "";
    }

C#停止,直到按下按钮

您可以禁用所有需要的按钮,直到再次需要为止。

void SetControlsAbility(bool isEnabled)
{
    // for every control you need:
    yourControl.Enabled = isEnabled;
}

然后

private void buttonSquareRoot_Click(object sender, EventArgs e)
{
    num1 = double.Parse(textBox1.Text);
    if (num1 < 0.0)
    {
        textBox1.Text = "Invalid Input";
        SetControlsAbility(false);
    }
    else
    {
        result = Math.Sqrt(double.Parse(textBox1.Text));
        textBox1.Text = Convert.ToString(result);
    }
}

private void buttonClear_Click(object sender, EventArgs e)
{
    textBox1.Text = "";
    SetControlsAbility(true);
}
private void buttonSquareRoot_Click(object sender, EventArgs e)
    {
        num1 = double.Parse(textBox1.Text);
        if (num1 < 0.0)
        {
            textBox1.Text = "Invalid Input";
            **buttonSquareRoot.Enabled = False;**
        }
        else
        {
            result = Math.Sqrt(double.Parse(textBox1.Text));
            textBox1.Text = Convert.ToString(result);
        }
    }

private void buttonClear_Click(object sender, EventArgs e)
    {
        textBox1.Text = "";
        buttonSquareRoot.Enabled = True;
    }