環境
・Visual Studio 2022
・.Net 9.0
・Windows Forms
やりたいこと
英数字や数値のみなど、入力させたい文字や文字数に制限を設けたい。
ないのが疑問に思うほどよく使われるような機能だと思いますが、デフォルトでは存在しないのでカスタムコントロールで独自で実装する。
実装方法
partial class CustomTextBox : TextBox
{
// 入力制限の種類を列挙型で定義
public enum InputTypes
{
AlphaNumeric, // 英数字
Numeric, // 数字のみ
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Description("入力タイプを設定します。")]
[Category("動作")]
public InputTypes InputType { get; set; } = InputTypes.AlphaNumeric;
public CustomTextBox()
{
}
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
string original = this.Text;
string newText = original;
// 入力タイプによって入力不可な文字を抜く
if (InputType == InputTypes.Numeric)
{
newText = new string(original.Where(c => char.IsDigit(c)).ToArray());
}
else if (InputType == InputTypes.AlphaNumeric)
{
newText = new string(original.Where(c => char.IsLetterOrDigit(c)).ToArray());
}
// 文字数制限
if(newText.Length > this.MaxLength)
{
newText = newText.Substring(0, this.MaxLength);
}
// 入力内容が変わっていたら更新
if (newText != original)
{
int selStart = this.SelectionStart;
this.Text = newText;
// キャレット位置を調整
this.SelectionStart = Math.Min(selStart, this.Text.Length);
}
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
}
}
上記のコードを追加したカスタムコントロールに記載すると、ツールボックスに追加されているのでデザイン上に配置。
プロパティにもInputTypeがあるのでそちらから設定を変更できます。
(ツールボックスやプロパティに出ないなどあればビルドしてみてください)
MaxLengthはデフォルトである文字数制限のプロパティで、キー入力では機能してくれますが、コード上からテキスト操作した際は機能してくれなかったので独自で追記しています。


