MDI親フォームの背景色の変更・背景への描画
MDIフォームの背景色の変更や背景への描画方法を紹介します。フォームのIsMdiContainerプロパティをTrueに設定し、MDI親フォームにするとフォームのBackColorプロパティを変更しても変更内容が反映されません。MDI親ウィンドウの背景色の変更や背景への描画は"MdiClient"コントロールを用います。
UI
下図のUIを準備します。
FormMain
IsMdiContainerプロパティを"True"にします。
FormSub
リソース
下図の画像をプロジェクトに追加します。画像のプロパティの[ビルドアクション]を"埋め込まれたリソース"に設定します。
コード
以下のコードを記述します。
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;
using System.IO;
using System.Reflection;
namespace DrawMDIParentForm
{
public partial class FormMain : Form
{
Bitmap bmp;
System.Windows.Forms.MdiClient mc;
public FormMain()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
FormChild fc = new FormChild();
fc.MdiParent = this;
fc.Show();
Assembly assembly = Assembly.GetExecutingAssembly();
Stream stream = assembly.GetManifestResourceStream("DrawMDIParentForm.logo.png");
bmp = new Bitmap(stream);
Graphics FormG = this.CreateGraphics();
bmp.SetResolution(FormG.DpiX, FormG.DpiY);
foreach (System.Windows.Forms.Control c in Controls) {
if (c is System.Windows.Forms.MdiClient) {
mc = (System.Windows.Forms.MdiClient)c;
mc.BackColor = Color.White;
mc.Paint += new PaintEventHandler(MDIClient_Paint);
mc.Resize += new EventHandler(MDIClient_Resize);
}
}
}
private void MDIClient_Paint(object sender, PaintEventArgs e)
{
if (bmp != null && mc != null) {
e.Graphics.DrawImage(bmp, new Point(mc.Width - bmp.Width-10, mc.Height - bmp.Height-10));
}
}
private void MDIClient_Resize(object sender, EventArgs e)
{
if (mc != null) {
mc.Invalidate();
}
}
}
}
解説
Loadイベント
FormChild fc = new FormChild();
fc.MdiParent = this;
fc.Show();
にて、MDI子フォームのインスタンス作成と表示をします。
Assembly assembly = Assembly.GetExecutingAssembly();
Stream stream = assembly.GetManifestResourceStream("DrawMDIParentForm.logo.png");
bmp = new Bitmap(stream);
Graphics FormG = this.CreateGraphics();
bmp.SetResolution(FormG.DpiX, FormG.DpiY);
リソースからロゴ画像を読み出します。SetResolutionについては
こちらの記事を参照してください
foreach (System.Windows.Forms.Control c in Controls) {
if (c is System.Windows.Forms.MdiClient) {
mc = (System.Windows.Forms.MdiClient)c;
mc.BackColor = Color.White;
mc.Paint += new PaintEventHandler(MDIClient_Paint);
mc.Resize += new EventHandler(MDIClient_Resize);
}
}
foreachループを用いてフォームのコントロールを列挙します。"System.Windows.Forms.MdiClient"であるコントロールを見つけ、BackColorプロパティを設定し背景色を変更します。また、PaintイベントとResizeイベントハンドラを設定します。
MdiClientのPaint,Resizeイベント
private void MDIClient_Paint(object sender, PaintEventArgs e)
{
if (bmp != null && mc != null) {
e.Graphics.DrawImage(bmp, new Point(mc.Width - bmp.Width-10, mc.Height - bmp.Height-10));
}
}
private void MDIClient_Resize(object sender, EventArgs e)
{
if (mc != null) {
mc.Invalidate();
}
}
MdiClientコントロールのPaintイベントとResizeイベントです。画面の描画や画面更新をします。
実行結果
プロジェクトを実行します。下図のウィンドウが表示されます。MDI親ウィンドウの背景が白になり、右下に画像が表示されています。
MDI親ウィンドウをリサイズすると画面が更新され、画像が右下に表示されます。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用