【问题标题】:TextBox1_KeyPress will not work anymore even though I haven't changed any code即使我没有更改任何代码,TextBox1_KeyPress 也将不再工作
【发布时间】:2015-11-11 00:21:15
【问题描述】:

最近我从 Visual Studio express 2013 切换到 Visual Studio Community 15。 当我用这段应该阻止字符输入的代码运行我的表单时,文本框只允许数字和小数(。)并且它运行完美,但是一旦我切换到社区 15,它就不再阻止字符输入。为什么?处理设置为假,只要它是一个数字或小数?

private void WeeklyCheckTxtBox_KeyPress(object sender, KeyPressEventArgs e)
    {
       if (char.IsDigit(e.KeyChar) || char.IsControl(e.KeyChar) || char.IsPunctuation('.'))
        {
            e.Handled = false;
        }
        else
        {
            e.Handled = true;
        }
    }

【问题讨论】:

    标签: c# visual-studio textbox keypress keyboard-events


    【解决方案1】:

    问题是 char.IsPunctuation('.') 将始终返回 true 作为 .毫无疑问是一个标点符号,所以这个事件永远不会被处理——我想你可能打算写e.KeyChar == '.'char.IsPunctuation(e.KeyChar)

    【讨论】:

    • 感谢@Ben Jackson 的帮助。 e.KeyChar == '.'正是我正在寻找的 e.KeyChar == '.'只允许 (.) 作为标点输入,而 char.IsPunctuation(e.KeyChar) 将允许其他我不想要的标点符号 (!,@,%,&,....)。
    猜你喜欢
    • 2023-04-03
    • 2011-04-30
    • 2017-08-13
    • 2023-03-30
    • 2016-08-21
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    • 2014-03-25
    相关资源
    最近更新 更多