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

C# 創建不規則窗體:CreatePolygonRgn + SetWindowRgn 實現

     編輯:關於C語言

利用 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(圓角矩形)等創建常見異形窗體。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved