表格,基本计算器按键触发问题

问题描述

 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();
            }
        }
    }

enter image description here

我正在编码一个基本的表格计算器。我试图触发加法功能并在文本框被聚焦并且用户按下“ +”键时清除文本框。 “ if (String.IsNullOrEmpty(UserInputText.Text))else条件很好。但是,如果没有出现消息框,如 在if (double.TryParse(UserInputText.Text,out sayı1))条件下,“ +”字符保留在图像中的文本框中。感谢您的帮助。

解决方法

如果我的理解正确,您想先检查键入的字符,如果输入不正确,那么您想阻止此字符出现吗?

如果是这样,那么您需要设置e.Handled = true属性来阻止它。

此呼叫告诉GUI元素(您的TextBox)“我已对此事件(即KeyDown事件进行了所有检查,但我不希望您为处理此事件做出贡献事件(即,通常TextBox会尝试将此字符添加到其Text属性中,但是您可以阻止它)”。

查看有关KeyEventArgs.Handled的文档。

,

KeyPress事件使您可以防止在TextBox中进行任何进一步的更改。 由于Handled的{​​{1}}属性,您可以做到这一点

KeyPressEventArgs

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...