在 Paint 事件繪製橢圓,系統卡頓時先顯示矩形窗體再裁剪,體驗差。
在窗體建立時 (建構子/Load) 呼叫 SetWindowRgn,系統級裁剪,**無閃爍、無繪製延遲**。
using System.Runtime.InteropServices;
public partial class EllipseForm : Form {
[DllImport("gdi32.dll")]
static extern IntPtr CreateEllipticRgn(int x1, int y1, int x2, int y2);
[DllImport("user32.dll")]
static extern int SetWindowRgn(IntPtr hWnd, IntPtr hRgn, bool bRedraw);
protected override void OnHandleCreated(EventArgs e) {
base.OnHandleCreated(e);
// 建立橢圓區域 (客戶區座標)
IntPtr hRgn = CreateEllipticRgn(0, 0, this.ClientSize.Width, this.ClientSize.Height);
SetWindowRgn(this.Handle, hRgn, true);
// 系統接管區域所有權,無需手動 DeleteObject
}
protected override void OnResize(EventArgs e) {
base.OnResize(e);
if (this.Handle != IntPtr.Zero) {
IntPtr hRgn = CreateEllipticRgn(0, 0, this.ClientSize.Width, this.ClientSize.Height);
SetWindowRgn(this.Handle, hRgn, true);
}
}
}
CreateRectRgn,CombineRgn(RGN_OR) 合成。GraphicsPath.AddPolygon + Region (GDI+),再 region.GetHrgn(Graphics) 轉 HRGN。完整範例:C# Win32 API 非矩形窗體