LoginSignup
0
0

C#でWindowsForm上のコントロールをすべて取得する

Last updated at Posted at 2023-01-28

1. はじめに

  • WindowsForm上の全コントロールを取得して処理を共通化したい

2. クラスの作成

  • WindwosフォームからControlを受け取ることで、フォーム上にあるコントロールを取得する
public static class GetControls
{
    public static void  Init<T>(this T control) where T : System.Windows.Forms.Control
    { 
        // コントロール全てを列挙
        List<Control> controls = GetAllControls<Control>(control);
        Debug.Print("controls : " + controls.Count().ToString());

        foreach (var ctl in controls)
        {
            // TODO: 仮実装
            Debug.Print("**********control : " + ctl.Name);
        }

        // ボタン、またはボタンを継承したコントロールを列挙
        List<Button> buttons = GetAllControls<Button>(control);
        System.Console.WriteLine("buttons : " + buttons.Count().ToString());

        foreach (var ctl in buttons)
        {
            // TODO: 仮実装
            Debug.Print("**********button : " + ctl.Name);
        }
    }

    /// <summary>
    /// 指定のコントロール上の全てのジェネリック型 Tコントロールを取得する。
    /// </summary>
    /// <typeparam name="T">対象となる型</typeparam>
    /// <param name="top">指定のコントロール</param>
    /// <returns>指定のコントロール上の全てのジェネリック型 Tコントロールのインスタンス</returns>
    private static List<T> GetAllControls<T>(Control top) where T : System.Windows.Forms.Control
    {
        List<T> buf = new List<T>();
        foreach (Control ctrl in top.Controls)
        {
            if (ctrl is T) buf.Add((T)ctrl);
            buf.AddRange(GetAllControls<T>(ctrl));
        }

        return buf;
    }
}

3. Windowsフォームを作成

  • Form_Load時に作成したクラスのInitメソッドを呼びだすようにする
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 作成したクラスのメソッドを呼び出す
            this.Init();
        }
    }

4. 動作確認

  • Windowsフォームに配置したコントロールが取得できることを確認

5. 参考文献

0
0
0

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
0
0