Aero Glassウィンドウで部分的に透過度を変える (Aero Glassウィンドウでの画像描画) - C#

Aero Glassのウィンドウの透過部分で部分的に透明度が異なる場所があります。
ウェブブラウザを例にしてみると非アクティブなタブや非アクティブなテキストボックスの背景の透明度が他より低いです。

Internet Explorer 9 (IE9) (RC)


Chrome 9


Internet Explorer 8 (IE8)


実装

フォームの一部の透明度を変えて表示する方法の一つとして、アルファ値のついている画像をフォームに描画することで実現できます。
下記の画像を用意します。

画像(img01.png)


背景色が白いため画面では画像が見えませんが上図の画像を用意します。
Photoshopで編集中の画像は下記の状態です。上半分が白いグラデーションになっていることがわかります。


コード

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.Runtime.InteropServices;

namespace AeroApplication
{
  public partial class MainForm : Form
  {
    [DllImport("dwmapi.dll")]
    private static extern int DwmIsCompositionEnabled(out bool enabled);

    [DllImport("dwmapi.dll", PreserveSig = true)]
    static extern int DwmExtendFrameIntoClientArea(IntPtr hwnd, ref MARGINS margins);

    //[DllImport("dwmapi.dll", PreserveSig = false)]
    //static extern void DwmExtendFrameIntoClientArea(IntPtr hwnd, ref MARGINS margins);

    [StructLayout(LayoutKind.Sequential)]
    public struct MARGINS
    {
      public int leftWidth;
      public int rightWidth;
      public int topHeight;
      public int bottomHeight;
    }
    
    public MainForm()
    {
      InitializeComponent();

      BackColor = Color.Black;

      bool DwmEnabled=false;
      DwmIsCompositionEnabled(out DwmEnabled);
      if (DwmEnabled == true) {
        MARGINS margin;
        margin.leftWidth=-1;
        margin.rightWidth=0;
        margin.topHeight=0;
        margin.bottomHeight=0;

        DwmExtendFrameIntoClientArea(this.Handle, ref margin); 
      }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
    }

    private void MainForm_Paint(object sender, PaintEventArgs e)
    {
      //Bitmap bmp = new Bitmap(@"img\paint.png");
      Bitmap bmp = new Bitmap(@"img\img01.png");
      e.Graphics.DrawImage(bmp, new Point(20,20));
      
      Font font = new Font(this.Font, FontStyle.Regular);
      Brush brush = new SolidBrush(Color.Black);
      e.Graphics.DrawString("Test Message", font, brush, new PointF(20,20)); 
    }
  }
}

解説

AeroGlassのウィンドウ作成についてはこちらの記事を参照してください。

実行結果

実行すると下図の画面が表示されます。フォームの一部分の透明度が異なる(強まっている)ように見えます。


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