【C#】別クラスのメソッドからフォームを操作する


この記事はプロモーションを含みます。

C#でフォームがあるクラスとは別のクラスにあるメソッドからフォームを操作する方法を解説します。

事前準備

まずは、動作確認するためのテキストボックスとボタンだけのフォーム画面を作成します。

テキストボックスのModifiers(保護レベル)が「Private」となっている場合は「Internal」に変更しないとビルドエラーが発生します。

上記フォームのソースコード(Form1.Designer.cs)です。

namespace WinFormsApp1
{
    partial class Form1
    {
        /// <summary>
        ///  Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        ///  Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        ///  Required method for Designer support - do not modify
        ///  the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            textBox1 = new TextBox();
            button1 = new Button();
            SuspendLayout();
            // 
            // textBox1
            // 
            textBox1.Location = new Point(12, 12);
            textBox1.Name = "textBox1";
            textBox1.Size = new Size(270, 23);
            textBox1.TabIndex = 2;
            // 
            // button1
            // 
            button1.Location = new Point(303, 12);
            button1.Name = "button1";
            button1.Size = new Size(75, 23);
            button1.TabIndex = 3;
            button1.Text = "button1";
            button1.UseVisualStyleBackColor = true;
            button1.Click += button1_Click;
            // 
            // Form1
            // 
            AutoScaleDimensions = new SizeF(7F, 15F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(392, 44);
            Controls.Add(button1);
            Controls.Add(textBox1);
            Name = "Form1";
            Text = "Form1";
            ResumeLayout(false);
            PerformLayout();
        }

        #endregion
        internal TextBox textBox1;
        private Button button1;
    }
}

サンプルコード

別クラスのメソッドからフォームを操作するためのソースコードです。
ここでは例として、ボタン押下時、テキストボックスに文字が入力されるようにします。
また、テキストボックスは「Form1.cs」で作成し、文字の入力処理は別クラスとなる「Util.cs」に作成します。

Form1.cs
namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Util util = new Util(this);
            util.Exec();
        }
    }
}
Util.cs
namespace WinFormsApp1
{
    public class Util
    {
        public Form1 _form1;

        public Util(Form1 form1)
        {
            _form1 = form1;
        }

        public void Exec()
        {
            _form1.textBox1.Text = "テスト";
        }
    }
}

実行イメージ

ボタンを押して、テキストボックスにテストと表示されれば正常に動いています。

static修飾子を使用する方法

コントロールにstatic修飾子を付けることでも別クラスからアクセスすることが可能です。
下記は、テキストボックスにstatic修飾子を付けた例です。(修正ファイルは「Form1.Designer.cs」)

こちらの方法には1つ注意点があります。
それは、デザインを変更すると「Form1.Designer.cs」が自動生成され、static修飾子が外れてしまいます。
再度付与すればいいのですが、デザインの変更時には注意が必要です。

~~~省略~~~
private Button button1;
internal static TextBox textBox1;
~~~省略~~~

static修飾子を付けたテキストボックスにアクセスするには以下のように記述します。

public void Exec()
{
    Form1.textBox1.Text = "テスト";
}

コメント

タイトルとURLをコピーしました