首页 > 解决方案 > 表格,基本计算器按键触发问题

问题描述

 private void UserInputText_KeyDown(object sender, KeyEventArgs e)
    {
        if ((e.KeyCode == Keys.D4 && e.Modifiers == Keys.Shift) || (e.KeyCode == Keys.Add))
        {
            if (String.IsNullOrEmpty(UserInputText.Text))
            {
                MessageBox.Show("Bir sayı giriniz.");
                UserInputText.Clear();
                return;
            }
            if (double.TryParse(UserInputText.Text, out sayı1))
            {
                CalculationResultText.Text = sayı1 + " + ";
                islem = "+";
                UserInputText.Clear();
            }
            else
            {

                MessageBox.Show("Sadece sayı değeri girebilirsiniz.");
                UserInputText.Clear();
            }
        }
    }

在此处输入图像描述

我正在编写一个基本表格计算器。当文本框聚焦并且用户按下“+”键时,我正在尝试触发添加功能并清除文本框。"if (String.IsNullOrEmpty(UserInputText.Text))并且else条件运行良好。但如果没有消息框显示在 if (double.TryParse(UserInputText.Text, out sayı1))条件中,“+”字符将保留在文本框中,如图所示。感谢您的帮助。

标签: c#winformscalculator

解决方案


KeyPress事件使您能够防止 TextBox 中的任何进一步更改。Handled你可以做到这一点,这要归功于KeyPressEventArgs

private void UserInputText_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == '+')
    {
        UserInputText.Clear();      
        e.Handled = true;
    }
}

推荐阅读