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

标签 c# winforms custom-controls

我一直在研究 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 .

没有必要重新发明轮子。

关于C# 窗体 : Is there any way to improve this simple custom Textbox code?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8572000/

相关文章:

c# - 如何关闭与另一个 WinForm 代码不同的 WinForm?

android - 使用自定义对话框时无法使用 onDismiss() - Android

javascript - 是否可以将计数添加到选择框?

c# - C# 和 Java 之间的 AES/CBC/NoPadding

c# - 错误还是我做错了什么?用户控件绘画

c# - 使用 msmq 和 wcf

c# - 处理新表格的正确方法

vb.net - 在设计时运行的控件、属性、事件和计时器

c# - Microsoft Graph API : HttpStatusCode 200, 内容长度-1?

c# - global.asax 中的 Application_Error 真的是处理错误的方法吗?