核心原理
- FormBorderStyle.None:移除標題列與邊框
- TransparencyKey = BackColor:指定顏色視為透明
- 重寫 OnPaint:繪製不規則形狀圖片
完整程式碼
public partial class Form1 : Form
{
Bitmap bit;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
bit = new Bitmap("heart.bmp");
bit.MakeTransparent(Color.Blue); // 將藍色背景設為透明
}
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.DrawImage(bit, new Point(0, 0));
}
private void label1_Click(object sender, EventArgs e)
{
this.Close(); // Label 點擊關閉視窗
}
}
設計器關鍵設定
this.FormBorderStyle = FormBorderStyle.None;
this.BackColor = SystemColors.Control;
this.TransparencyKey = SystemColors.Control;
this.StartPosition = FormStartPosition.CenterScreen;
// Label 設為透明背景,置於右上角作關閉鈕
this.label1.BackColor = Color.Transparent;
this.label1.Location = new Point(280, 42);
this.label1.Click += label1_Click;
運作流程
- 載入含透明色 (藍色) 的 BMP 圖片
MakeTransparent(Color.Blue) 將藍色像素標記為透明
- 視窗背景色設為
Control,並指定為 TransparencyKey
OnPaint 繪製圖片,透明區域讓視窗「鏤空」
- 點擊透明 Label 關閉視窗
應用延伸
- 任意形狀視窗:圓形、多邊形、角色剪影
- 桌面小工具、播放器皮膚、通知氣泡
- 搭配
Region 可實現點擊穿透特定區域