簡體   English   中英

將多個文本框限制為數字

[英]Limit multiple textbox to number

我找到了以下將文本框限制為數字的解決方案。 我的 GUI 中有 20 個文本框,有沒有比制作 20 個這些功能更簡潔的方法?

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

我的建議是用一個自定義控件替換需要此功能的標准文本框控件,該自定義控件還可以在控件中粘貼文本或在設計器中使用 PropertyGrid 設置控件的Text屬性時過濾用戶輸入。

如果只處理KeyPress事件,則無法防止錯誤粘貼。
我認為最好過濾Text屬性中設置的內容,以避免誤解

測試這個簡單的自定義文本框控件:它處理直接用戶輸入和在運行時粘貼的文本。 UserPaste屬性設置為Disallow ,將忽略粘貼,而將其設置為NumbersOnly (默認)僅允許數字:如果在控件中粘貼混合字符,則僅保留數字。

要還允許輸入逗號和點,請更改[^0-9,.\b]中的正則表達式。

Designer 中設置的 Text 屬性也會被過濾。

要使用此自定義控件替換現有的 TextBox 控件,您可以在 Visual Studio 中使用查找/替換 function(通常使用CTRL+H激活):

using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Windows.Forms;

[ToolboxItem(true)]
[DesignerCategory("Code")]
public class TextBoxNumbers : TextBox
{
    private Regex regex = new Regex(@"[^0-9\b]", RegexOptions.Compiled);

    public TextBoxNumbers() { }

    public override string Text {
        get => base.Text;
        set { if (!base.Text.Equals(value)) base.Text = regex.Replace(value, ""); }
    }

    public enum PasteAction {
        NumbersOnly,
        Disallow
    }

    [DefaultValue(PasteAction.NumbersOnly)]
    public PasteAction UserPaste { get; set; }

    protected override void OnKeyPress(KeyPressEventArgs e)
    {
        if (regex.IsMatch(e.KeyChar.ToString())) {
            e.Handled = true;
        }
        base.OnKeyPress(e);
    }

    protected override void WndProc(ref Message m)
    {
        switch (m.Msg) {
            case NativeMethods.WM_PASTE:
                switch (UserPaste) {
                    case PasteAction.Disallow:
                        return;
                    case PasteAction.NumbersOnly:
                        string text = Clipboard.GetText(TextDataFormat.UnicodeText);
                        text = regex.Replace(text, "");
                        NativeMethods.SendMessage(this.Handle, NativeMethods.EM_REPLACESEL, 1, text);
                        return;
                }
                break;
        }
        base.WndProc(ref m);
    }
}

NativeMethods class:

using System.Runtime.InteropServices;

private class NativeMethods
{
    internal const int WM_PASTE = 0x0302;
    internal const int EM_REPLACESEL = 0xC2;

    [DllImport("User32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    internal static extern int SendMessage(IntPtr hWnd, uint uMsg, int wParam, string lParam);
}

我的簡單而首選的解決方案是編寫一次方法,然后將 go 寫入設計器和 select 每個需要它的 texbox,單擊屬性中的事件按鈕,滾動到 KeyPress 事件並單擊它曾經,現在應該出現一個下拉箭頭,select 你的方法在那里 - 完成。

private void textBox_KeyPress(object sender, KeyPressEventArgs e)
 {
     e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
 }

暫無
暫無

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

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