【C#】ウィンドウ内での画面遷移をコントロール切り替えで実装
C#を初めて触って簡単なところにもかかわらず躓いたのでメモ。サンプルアプリはページ下部にGitHupへのリンクがあるのでそちらから。
0.作成するプログラム
あるウィンドウ上のボタン操作によって表示画面が切り替わるプログラム。イメージ(完成品)は以下の通り。
↓button1を押す button2を押す↑
初心者的感覚で上の動作を言語化すると「C#のフォームアプリケーションでウィンドウ内の画面遷移をしたい」だったのだが、これらのキーワードではなかなか思い通りのページに辿り着けなかった。より良い実装も存在するように思うが、ページ数が少ないうちは結構簡単でいいと思っている。
1.プロジェクト作成
Visual Studio 2013の場合はプロジェクトを新規作成し、C#のWindowsフォームアプリケーションを選択する。
フォーム上にPanelコントロールを画面いっぱいに配置。このPanelコントロールにあらかじめ表示したいページを登録しておいて、ボタンクリックイベントが発生した時にどのページを表示するか選択する方針で実装。遷移先の2ページは個別にレイアウトを検討したいのでユーザコントロールとして作成した。下図参照。
2.ページ遷移のコード
ポイントは2つのユーザコントロールをForm.cs内でpublic staticで確保すること。これによりUserControl1とUserControl2からもそれぞれのインスタンス(ctr1とctr2)にアクセスしてVisibleの値を変更できる。
Form1.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; namespace WindowsFormsApplication3 { public partial class Form1 : Form { //staticで宣言することでインスタンスを固定 public static UserControl1 ctr1; public static UserControl2 ctr2; public Form1() { InitializeComponent(); ctr1 = new UserControl1(); ctr2 = new UserControl2(); //パネルにコントロール1、2を追加 panel1.Controls.Add(ctr1); panel1.Controls.Add(ctr2); //コントロール1のみを見えるようにする ctr1.Visible = true; ctr2.Visible = false; } private void Form1_Load(object sender, EventArgs e) { } private void panel1_Paint(object sender, PaintEventArgs e) { } } }
UserControl1.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication3 { public partial class UserControl1 : UserControl { public UserControl1() { InitializeComponent(); } private void UserControl1_Load(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { Form1.ctr1.Visible = false; Form1.ctr2.Visible = true; } } }
UserControl2.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication3 { public partial class UserControl2 : UserControl { public UserControl2() { InitializeComponent(); } private void button2_Click(object sender, EventArgs e) { Form1.ctr1.Visible = true; Form1.ctr2.Visible = false; } } }
今回作成したSW
GitHub - whg-res/cs_form_jump_sample: c# form application page jump example
※参考
https://github.com/whg-res/cs_form_jump_sample/
http://blog.hiros-dot.net/?p=4815
http://qa.atmarkit.co.jp/q/4935