傳統矩形視窗無法滿足現代 UI 設計需求。透過設定 FormBorderStyle=None、TransparencyKey 與背景圖片,配合滑鼠拖曳邏輯,即可輕鬆打造任意形狀的不規則視窗,無需複雜的 API 呼叫。
#FFFFFF 或洋紅 #FF00FF)。TransparencyKey 設為透明。
| 屬性 | 設定值 | 說明 |
|---|---|---|
| FormBorderStyle | None | 移除標題列與邊框 |
| BackgroundImage | 你的圖片檔 | 設為視窗背景 |
| TransparencyKey | 圖片背景色 (如 White) | 指定透明色,該顏色像素將不繪製 |
| StartPosition | CenterScreen | 置中顯示 |
PictureBox 作為關閉鈕,設定 Click 事件呼叫 this.Close()。ContextMenuStrip,加入「結束」選項,同樣呼叫 Close(),並設定為表單的 ContextMenuStrip。無標題列視窗預設無法拖曳,需自行處理滑鼠事件:
using System;
using System.Drawing;
using System.Windows.Forms;
public class IrregularForm : Form
{
private Point _mouseOffset;
private bool _isMouseDown;
private PictureBox _closeBtn;
private ContextMenuStrip _contextMenu;
public IrregularForm()
{
InitializeComponent();
SetupDrag();
}
private void InitializeComponent()
{
// 視窗基本設定
FormBorderStyle = FormBorderStyle.None;
BackgroundImage = Image.FromFile("YourSkin.png"); // 載入圖片
TransparencyKey = Color.White; // 透明色
ClientSize = new Size(365, 235);
StartPosition = FormStartPosition.CenterScreen;
// 關閉按鈕
_closeBtn = new PictureBox
{
Image = Image.FromFile("CloseBtn.png"),
Location = new Point(290, 8),
SizeMode = PictureBoxSizeMode.AutoSize
};
_closeBtn.Click += (s, e) => Close();
Controls.Add(_closeBtn);
// 右鍵選單
_contextMenu = new ContextMenuStrip();
_contextMenu.Items.Add("結束").Click += (s, e) => Close();
ContextMenuStrip = _contextMenu;
}
private void SetupDrag()
{
MouseDown += (s, e) =>
{
if (e.Button == MouseButtons.Left)
{
// 計算滑鼠相對視窗左上角的偏移量
_mouseOffset = new Point(-e.X, -e.Y);
_isMouseDown = true;
}
};
MouseMove += (s, e) =>
{
if (_isMouseDown)
{
// 取得螢幕座標並套用偏移
Point screenPos = PointToScreen(e.Location);
screenPos.Offset(_mouseOffset);
Location = screenPos;
}
};
MouseUp += (s, e) =>
{
if (e.Button == MouseButtons.Left)
_isMouseDown = false;
};
}
[STAThread]
static void Main() => Application.Run(new IrregularForm());
}
| 問題 | 原因與解決 |
|---|---|
| 透明色無效,非透明區域仍顯示背景色 | 螢幕色深大於 24-bit 時 TransparencyKey 可能失效。解決:將專案目標框架設為 .NET Framework 4.7+,或改用 SetWindowRgn API 定義視窗區域。 |
| 視窗閃爍 | 啟用雙緩衝:SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true)。 |
| 無法接收鍵盤焦點 | 覆寫 CreateParams 加入 WS_EX_NOACTIVATE 或處理 WM_NCHITTEST。 |
OnPaint 使用 Graphics 繪製,或使用 WPF 獲得更豐富視覺效果。WndProc 處理 WM_NCHITTEST,根據圖片 Alpha 通道判斷點擊區域。AutoScaleMode = AutoScaleMode.Dpi 並提供多解析度圖片資源。利用 TransparencyKey 製作不規則視窗是 WinForms 中最簡單、效能最好的方式。配合滑鼠拖曳邏輯,即可快速打造具備品牌特色的客製化介面。對於極度複雜的非矩形互動需求,建議考慮遷移至 WPF 或使用 SetWindowRgn API 精確控制視窗區域。