利用 GDI CreatePolygonRgn 創建多邊形區域,配合 SetWindowRgn 設置窗體顯示區域,實現非矩形窗體(如五邊形、圓形、任意多邊形)。
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace APIDemo
{
public partial class Form1 : Form
{
[StructLayout(LayoutKind.Sequential)]
private struct POINT { public int X; public int Y; }
[DllImport("gdi32.dll")]
private static extern IntPtr CreatePolygonRgn(ref POINT points, int count, int mode);
[DllImport("user32.dll")]
private static extern int SetWindowRgn(IntPtr hWnd, IntPtr hRgn, ref bool redraw);
public Form1()
{
InitializeComponent();
// 定義五邊形頂點
POINT[] pts = new POINT[5];
pts[0] = new POINT { X = 90, Y = 90 };
pts[1] = new POINT { X = Width, Y = 0 };
pts[2] = new POINT { X = Width, Y = Height / 2 };
pts[3] = new POINT { X = Width / 2, Y = Height / 2 };
pts[4] = new POINT { X = 0, Y = Width };
bool redraw = true;
IntPtr hRgn = CreatePolygonRgn(ref pts[0], 5, 1); // ALTERNATE 模式
SetWindowRgn(Handle, hRgn, ref redraw);
BackColor = Color.BurlyWood;
}
// 置頂/取消置頂演示
[DllImport("user32.dll")]
private static extern int SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int y, int cx, int cy, int flags);
private void btnTopMost_Click(object sender, EventArgs e)
{
SetWindowPos(Handle, -1, 0, 0, 0, 0, 1); // HWND_TOPMOST
}
private void btnNormal_Click(object sender, EventArgs e)
{
SetWindowPos(Handle, -2, 0, 0, 0, 0, 0); // HWND_NOTOPMOST
}
}
}
CreatePolygonRgn 參數:頂點數組、頂點數、填充模式(1=ALTERNATE, 2=WINDING)。SetWindowRgn 會取得區域所有權,**區域刪除由系統負責**,無需手動 DeleteObject。Resize 事件中處理)。同理可用 CreateEllipticRgn(橢圓)、CreateRoundRectRgn(圓角矩形)等創建常見異形窗體。