如何限制文本框只接受特定字符

How to limit textbox to accept only specific characters

我想知道如何在 C# 表单应用程序中限制文本框的特定字符数。 例如我想限制用户输入 - (minus) 一次 然后如果他再次尝试输入我希望程序再次限制输入。

示例: -123 or 123- or 123-123 (only one -).

如果用户 删除 - 那么应该有权再次输入一个 - 当然不能再输入了!

我想阻止用户输入----12341234--,或123-4--21或你认为的更多!!

这是我正在尝试的:

private void txtStopAfterXTimes_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.OemMinus || e.KeyCode == Keys.Subtract)
    {
        if (txtStopAfterXTimes.Text.Count((char)'-', 1))
        {
            e.SuppressKeyPress = true;
        }
        else if (txtStopAfterXTimes.Text.Count((char)'-', 0))
        {
            e.SuppressKeyPress = false;
        }
    }
}

我知道这是错误的,但请帮忙! 谢谢...

您可以通过 2 方式更改 txtStopAfterXTimes 中的 Text 一个键(-) 或通过粘贴 一个值。 这就是为什么我们必须处理 2 事件:KeyPress 用于 - 按键和 TextChanged 用于文本粘贴:

代码: (WinForms)

private void txtStopAfterXTimes_TextChanged(object sender, EventArgs e) {
  // When pasting a text into txtStopAfterXTimes...
  TextBox box = sender as TextBox;

  StringBuilder sb = new StringBuilder(box.Text.Length);

  bool containsMinus = false;

  // We remove all '-' but the very first one
  foreach (char ch in box.Text) {
    if (ch == '-') {
      if (containsMinus)
        continue;

      containsMinus = true;
    }

    sb.Append(ch);
  }

  box.Text = sb.ToString();
}

private void txtStopAfterXTimes_KeyPress(object sender, KeyPressEventArgs e) {
  TextBox box = sender as TextBox;

  // we allow all characters ...
  e.Handled = e.KeyChar == '-' &&             // except '-'
              box.Text.Contains('-') &&       // when we have '-' within Text
             !box.SelectedText.Contains('-'); // and we are not going to remove it
}

我会避免使用 TextChanged,因为它会在文本更改后引发,而且可能有点晚。

这是我将使用的解决方案,因为您还需要关心粘贴。

  • keyPress我检查字符是否不是第一个“-”,那么我就忽略它,否则我就接受它。
  • WndProc 上,我捕获 WM_PASTE 并清理剪贴板文本,删除所有出现的“-”,但第一个。如果输入不可接受,您也可以轻松决定停止粘贴。

实现如下:

using System.Runtime.InteropServices;
using System.Windows.Forms;
public class MyTextBox : TextBox
{
    private const int WM_PASTE = 0x0302;
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern bool MessageBeep(int type);
    protected override void WndProc(ref Message m)
    {
        if (m.Msg != WM_PASTE) { base.WndProc(ref m); }
        else {
            //You can sanitize the input or even stop pasting the input
            var text = SanitizeText(Clipboard.GetText());
            SelectedText = text;
        }
    }
    protected virtual string SanitizeText(string value)
    {
        if (Text.IndexOf('-') >= 0) { return value.Replace("-", ""); }
        else {
            var str = value.Substring(0, value.IndexOf("-") + 1);
            return str + value.Substring(str.Length).Replace("-", "");
        }
    }
    protected override void OnKeyPress(KeyPressEventArgs e)
    {
        if (e.KeyChar == '-' && this.Text.IndexOf('-') >= 0) {
            e.Handled = true;
            MessageBeep(0);
        }
        else {
            base.OnKeyPress(e);
        }
    }
}