在 Windows Forms TextBox 中出现之前,如何将按键点击限制为仅限数字?

How to constrain keyclicks to digits only, before they are seen in a Windows Foms TextBox?

我的应用程序要求输入一个数字,该数字应限制为:

我相信我通过使用 TextChanged WinForms 事件找到了实现大部分要求的正确方法。

我需要帮助的部分是防止看到任何非数字击键,即使是几分之一秒。需要某种回显 cancellation/replacement。

您可以使用 NumericUpDown control or a MaskedTextBox control (a MSDN docs Walkthrough on its use), or maybe a Custom one, like this CodeProject MaskedEdit control or this other: FlexMaskEditBox.

这是与您的问题相关的手动实现:

首先,将 TextBox MaxLenght 属性 设置为 3,这样它将限制输入最多 3 个数字。

过滤用户按键仅接受数字和退格键:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar != (char)Keys.Back & !char.IsDigit(e.KeyChar))
        e.Handled = true;
}

确保第一个位置没有插入 Keys.D0:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.D0)
    {
        if (textBox1.Text.Length == 0 || textBox1.SelectionStart == 0)
            e.SuppressKeyPress = true;
    }
}

反粘贴:如果插入的文本无法翻译成 Integer 数字,则拒绝突然更改 TextBox 文本。
删除错误位置的 0s 和其他非数字字符:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (textBox1.Text.Length > 0)
    {
        if (textBox1.Text.Substring(0, 1) == "0")
            textBox1.Text = textBox1.Text.Substring(1);
        else
            if (!int.TryParse(textBox1.Text, out int Number))
            textBox1.Text = string.Empty;
    }
}