Skip to main content
 首页 » 编程设计

C# 窗体 : Is there any way to improve this simple custom Textbox code

2024年02月23日17myhome

我一直在研究 Custom TextBox 控件,它只允许字母数字字符。请注意,我没有限制来自 KeyPress、KeyUp 事件的字符,因为我不想限制复制/粘贴或任何其他通常应该允许的操作。我只在粘贴操作中修剪了非字母数字字符。但是,我不确定我写的代码是好是坏,因为我对桌面应用程序的经验很少。

using System; 
using System.Windows.Forms; 
using System.Text.RegularExpressions; 
 
namespace SaintThomas.UserControls 
{ 
    class TextBoxForUserName : TextBox 
    { 
        protected override void OnTextChanged(EventArgs e) 
        { 
            base.OnTextChanged(e); 
 
            this.SuspendLayout(); 
            int startPos = this.SelectionStart; 
            if (Regex.IsMatch(this.Text, "[^0-9_A-Z]", RegexOptions.IgnoreCase)) 
            { 
                int reduceStartPos = this.Text.Length; 
                this.Text = Regex.Replace(this.Text, "[^0-9_A-Z]", "", RegexOptions.IgnoreCase); 
                startPos = (startPos <= 0) ? 0 : startPos - (reduceStartPos - this.Text.Length); 
                if (this.Text.Length < startPos) 
                { 
                    startPos = this.Text.Length; 
                } 
                this.SelectionStart = startPos; 
            } 
            this.ResumeLayout(); 
        } 
    } 
} 

请您参考如下方法:

最好的方法是使用 MaskedTextBox control .

没有必要重新发明轮子。