1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【WindowsForm】TextBoxで入力制限

1
Last updated at Posted at 2025-10-19

環境

・Visual Studio 2022
・.Net 9.0
・Windows Forms

やりたいこと

英数字や数値のみなど、入力させたい文字や文字数に制限を設けたい。
ないのが疑問に思うほどよく使われるような機能だと思いますが、デフォルトでは存在しないのでカスタムコントロールで独自で実装する。

実装方法

カスタムコントロールを追加。
スクリーンショット 2025-09-06 173503.png

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はデフォルトである文字数制限のプロパティで、キー入力では機能してくれますが、コード上からテキスト操作した際は機能してくれなかったので独自で追記しています。

スクリーンショット 2025-09-06 215117.png
スクリーンショット 2025-09-06 215201.png

株式会社ONE WEDGE

1
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?