UserControls/PatternSearchBoxControl.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ChatworkBulkSender.Utils;

namespace ChatworkBulkSender.UserControls
{
    [DesignerCategory("UserControl")]
    public partial class PatternSearchBoxControl : BaseSearchControl
    {
        // エラー表示用ツールチップ
        private ToolTip errorToolTip = new ToolTip();
        
        public PatternSearchBoxControl()
        {
            InitializeComponent();
            InitializeControls();

            // 既存のデザイナーで作成されたコントロールを基底クラスのフィールドに割り当て
            base._panel = this.panel;
            base._lblSearchBox = this.lblSearchBox;
            base._panelSearchBox = this.panelSearchBox;
            base._btnSearch = this.btnSearch;
            base._chkUnusedData = this.chkUnusedData;

            // テキストボックスの登録
            base._searchTextBoxes["ManagementNumber"] = this.mgmtNumberTxtBox;
            base._searchTextBoxes["PatternName"] = this.PattrernNameTxtBox;
            base._searchTextBoxes["CustomerName"] = this.customerNameTxtBox;

            // パターンID(管理番号)テキストボックスのイベントハンドラを設定
            this.mgmtNumberTxtBox.TextChanged += MgmtNumberTxtBox_TextChanged;
            this.mgmtNumberTxtBox.KeyPress += MgmtNumberTxtBox_KeyPress;
            
            // 各テキストボックスの最大文字数を設定
            this.mgmtNumberTxtBox.MaxLength = 10;      // 管理番号は10桁まで
            this.PattrernNameTxtBox.MaxLength = 50;    // パターン名称は50文字まで
            this.customerNameTxtBox.MaxLength = 100;   // 顧客名は100文字まで

            // 検索ボタンのイベントハンドラを設定
            this.btnSearch.Click += base.BtnSearch_Click;

            this.ActiveControl = null;
        }

        protected override void AdjustLayout()
        {
            if (IsInDesignMode()) { return; }

            // Null チェック
            if (_panelSearchBox == null || _btnSearch == null || _chkUnusedData == null)
                return;

            // サイズが0の場合もスキップ
            if (_panelSearchBox.Width <= 0 || _panelSearchBox.Height <= 0)
                return;

            // フォントサイズに合わせて高さを調整(213px → 250px)
            _panelSearchBox.Height = 250;

            // 検索条件ラベルの位置を元の位置に保つ
            if (_lblSearchBox != null)
            {
                _lblSearchBox.Location = new System.Drawing.Point(49, 15);
            }

            // 基底クラスのレイアウト調整を呼び出し(ボタンとチェックボックスの位置は基底クラスで設定)
            base.AdjustLayout();

        }

        protected override bool ValidateSearchCriteria(out string errorMessage)
        {
            errorMessage = string.Empty;
            var errors = new List<string>();
            
            // パターンID(管理番号)のバリデーション
            if (!string.IsNullOrWhiteSpace(mgmtNumberTxtBox.Text))
            {
                if (!ValidationHelperUtil.IsValidManagementNumber(mgmtNumberTxtBox.Text))
                {
                    errors.Add("パターンIDは1以上の半角数字で入力してください。");
                }
            }
            
            if (errors.Any())
            {
                errorMessage = string.Join("\n", errors);
                return false;
            }
            
            return true;
        }

        /// <summary>
        /// パターンIDテキストボックスのKeyPressイベントハンドラ
        /// </summary>
        private void MgmtNumberTxtBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            // バックスペース、Delete、Ctrl+V は許可
            if (e.KeyChar == '\b' || char.IsControl(e.KeyChar))
            {
                return;
            }

            // 数字以外の入力時
            if (!char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
                
                // ツールチップでエラーメッセージを表示
                errorToolTip.Show("半角数字のみ入力可能です", mgmtNumberTxtBox, 0, -25, 2000);
            }
        }

        /// <summary>
        /// パターンIDテキストボックスのTextChangedイベントハンドラ
        /// </summary>
        private void MgmtNumberTxtBox_TextChanged(object sender, EventArgs e)
        {
            // 先頭のゼロを削除する処理
            if (!string.IsNullOrWhiteSpace(mgmtNumberTxtBox.Text))
            {
                string text = mgmtNumberTxtBox.Text;
                
                // 先頭の0を削除(001 → 1)
                if (text.Length > 1 && text.StartsWith("0"))
                {
                    if (int.TryParse(text, out int number))
                    {
                        mgmtNumberTxtBox.Text = number.ToString();
                        // カーソルを末尾に移動
                        mgmtNumberTxtBox.SelectionStart = mgmtNumberTxtBox.Text.Length;
                    }
                }
                
                // バリデーション
                if (!ValidationHelperUtil.IsValidManagementNumber(mgmtNumberTxtBox.Text))
                {
                    // 背景色を薄い赤にして視覚的にエラーを示す
                    mgmtNumberTxtBox.BackColor = Color.FromArgb(255, 230, 230);
                    errorToolTip.Show("パターンIDは1以上の半角数字で入力してください。", 
                        mgmtNumberTxtBox, 0, -25, 3000);
                }
                else
                {
                    // 正常な場合は背景色を元に戻す
                    mgmtNumberTxtBox.BackColor = SystemColors.Window;
                    errorToolTip.Hide(mgmtNumberTxtBox);
                }
            }
            else
            {
                // 空の場合も背景色を元に戻す
                mgmtNumberTxtBox.BackColor = SystemColors.Window;
                errorToolTip.Hide(mgmtNumberTxtBox);
            }
        }

    }
}