ビジュアルスタイルが適用されたコントロールをフォームのキャンバスに描画したい場合がります。(ウィンドウを閉じるクローズボタンをフォームに描画させる場合など)
ビジュアルスタイルが適用されたコントロールを描画する場合にはVisualStyleRendererクラスを用います。
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.Windows.Forms.VisualStyles;
namespace App
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private VisualStyleRenderer _CloseButtonRenderer = null;
private void Form1_Paint(object sender, PaintEventArgs e)
{
if (Application.RenderWithVisualStyles){
if (VisualStyleRenderer.IsElementDefined(VisualStyleElement.Window.CloseButton.Normal)) {
if (_CloseButtonRenderer == null) {
_CloseButtonRenderer
= new VisualStyleRenderer(VisualStyleElement.Window.CloseButton.Normal);
}
_CloseButtonRenderer.DrawBackground(e.Graphics, new Rectangle(10, 10, 20, 40));
}
}
else {
ControlPaint.DrawCaptionButton(
e.Graphics, new Rectangle(10, 10, 20, 40),
CaptionButton.Close, ButtonState.Normal);
}
}
}
}
まず VisualStyleRenderer を宣言します。
で描画するコントロールが定義されているか確認します。
にてVisualStyleRendererを作成します。このVisualStyleRendererでフォームの閉じるボタンの標準状態の画像を描画できます。
指定したGraphicsオブジェクトの (X=10,y=10)に幅20ピクセル、高さ40ピクセルの閉じるボタンが描画されます。
ビジュアルスタイルが有効でない場合は、ControlPaintクラスを用いてビジュアルスタイルが有効でない閉じるボタンを描画します。