[C#] ウィンドウビジュアルスタイルが有効なコントロール(ボタンや各種ウィンドウ部品)をキャンバスに描画する
ウィンドウビジュアルスタイルが有効なコントロール(ボタンや各種ウィンドウ部品)をキャンバスに描画する
このページのタグ:[C#]
ビジュアルスタイルが適用されたコントロールをフォームのキャンバスに描画したい場合がります。(ウィンドウを閉じるクローズボタンをフォームに描画させる場合など)
ビジュアルスタイルが適用されたコントロールを描画する場合には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);
      }
    }
  }
}
コードの説明
private VisualStyleRenderer _CloseButtonRenderer = null;
まず VisualStyleRenderer を宣言します。
Application.RenderWithVisualStyles
でビジュアルスタイルが有効かチェックします。
VisualStyleRenderer.IsElementDefined(VisualStyleElement.Window.CloseButton.Normal)
で描画するコントロールが定義されているか確認します。
_CloseButtonRenderer = new VisualStyleRenderer(VisualStyleElement.Window.CloseButton.Normal);
にてVisualStyleRendererを作成します。このVisualStyleRendererでフォームの閉じるボタンの標準状態の画像を描画できます。
_CloseButtonRenderer.DrawBackground(e.Graphics, new Rectangle(10, 10, 20, 40));
指定したGraphicsオブジェクトの (X=10,y=10)に幅20ピクセル、高さ40ピクセルの閉じるボタンが描画されます。

ビジュアルスタイルが有効でない場合は、ControlPaintクラスを用いてビジュアルスタイルが有効でない閉じるボタンを描画します。
登録日 :2010-07-27
最終更新日 :2010-07-27
このページのタグ:[C#]