私は英数字のみを許可するカスタムTextBoxコントロールに取り組んでいます。 KeyPress、KeyUpイベントの文字を制限していないことに注意してください。コピー/ペーストやその他の操作を制限したくないので、一般的に許可する必要があります。私はペースト操作時に英数字以外の文字をトリミングしています。しかし、デスクトップアプリケーションの経験がほとんどないので、私が書いたコードが良いか悪いかはわかりません。C#Winforms:この単純なカスタムテキストボックスコードを改善する方法はありますか?
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();
}
}
}
[コードレビュー](http://codereview.stackexchange.com/) – V4Vendetta
ちょっと、コードレビューは優れたアイデアです。この投稿をCode Reviewに直接切り替えることができますか、または私はそれを再投稿する必要がありますか? –