首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 特殊視窗製作:任意形狀視窗 (透過 TransparencyKey 與 OnPaint 繪製)

     編輯:關於C語言

核心原理

  1. FormBorderStyle.None:移除標題列與邊框
  2. TransparencyKey = BackColor:指定顏色視為透明
  3. 重寫 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;

運作流程

  1. 載入含透明色 (藍色) 的 BMP 圖片
  2. MakeTransparent(Color.Blue) 將藍色像素標記為透明
  3. 視窗背景色設為 Control,並指定為 TransparencyKey
  4. OnPaint 繪製圖片,透明區域讓視窗「鏤空」
  5. 點擊透明 Label 關閉視窗

應用延伸

  • 任意形狀視窗:圓形、多邊形、角色剪影
  • 桌面小工具、播放器皮膚、通知氣泡
  • 搭配 Region 可實現點擊穿透特定區域
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved