簡體   English   中英

如何限制文本框 c# 表單應用程序的特定字符的數量

[英]How to limit number of specific character of a textbox c# form application

我想知道如何限制 c# 表單應用程序中文本框的特定字符的數量。 例如,我想限制用戶只能輸入-減號一次,然后如果他再次嘗試輸入,我希望程序再次限制輸入。

示例: -123123-123-123只有一個- )。

如果用戶刪除-那么應該有權限輸入一個-再次,當然沒有更多!

我想阻止用戶輸入----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;
        }
    }
}

我知道這是錯誤的,但請幫忙! 謝謝你...

您可以通過兩種方式更改txtStopAfterXTimesText一個鍵 ( - ) 或粘貼一個值。 這就是為什么我們必須處理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);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM