目次

フォームをアクティブにする - 別のフォームにフォーカスを移す - C#

別のフォームにフォーカスを移す方法を紹介します。

UI

下図のUIを作成します。

コード

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MultiFormActivate
{
  public partial class FormMain : Form
  {
    FormSub1 fs1;
    FormSub2 fs2;

    public FormMain()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      fs1 = new FormSub1();
      fs2 = new FormSub2();
      fs1.Owner = this;
      fs2.Owner = this;

      fs1.Show();
      fs2.Show();
    }

    private void button2_Click(object sender, EventArgs e)
    {
      fs1.Activate();
    }

    private void button3_Click(object sender, EventArgs e)
    {
      fs2.Activate();
    }
  }
}

解説

FormのActivateメソッドを呼び出すと、そのフォームをアクティブ化できます。アクティブ化されたフォームは前面に表示されフォーカスが移ります。

実行結果

アプリケーションを実行します。下図のウィンドウが表示されます。


Button1をクリックします。サブフォームが表示されます。


Button2をクリックするとSubForm1がアクティブ化され、前面に表示されます。また、フォーカスも移動します。


Button3をクリックするとSubForm2がアクティブ化されます。


著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-01-06
作成日: 2012-04-29
iPentec all rights reserverd.