C# WinForm 窗体或控件设置圆角

网上查找资料看到的大神讲解。

自己整理记录一下,以便以后用到

封装的函数

        #region 画圆角
        /// <summary>
        /// 设置窗体的圆角矩形
        /// </summary>
        /// <param name="form">须要设置的窗体</param>
        /// <param name="rgnRadius">圆角矩形的半径</param>
        public static void SetFormRoundRectRgn(Form form, int rgnRadius=20)
        {
            int hRgn = 0;
            hRgn = Win32.CreateRoundRectRgn(0, 0, form.Width + 1, form.Height + 1, rgnRadius, rgnRadius);
            Win32.SetWindowRgn(form.Handle, hRgn, true);
            Win32.DeleteObject(hRgn);
        }
        /// <summary>
        /// 设置控件的圆角矩形
        /// </summary>
        public static void SetCtrlRoundRectRgn(IntPtr handel, int width, int height, int rgnRadius)
        {
            int hRgn = 0;
            hRgn = Win32.CreateRoundRectRgn(0, 0, width + 1, height + 1, rgnRadius, rgnRadius);
            Win32.SetWindowRgn(handel, hRgn, true);
            Win32.DeleteObject(hRgn);
        }

        /// <summary>
        /// 设置panel控件的圆角
        /// </summary>
        /// <param name="pnl"></param>
        public static void SetPanelRoundRectRgn(Panel pnl, int rgnRadius = 15)
        {
            //调用上面的第二个函数
            SetCtrlRoundRectRgn(pnl.Handle, pnl.Width, pnl.Height, rgnRadius);
        }
        #endregion

cs文件


using System;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Windows.Forms;
using System.Collections;

/// <summary>
/// Wind32API声明
/// </summary>
public class Win32
{
    public const int GWL_EXSTYLE = -20;
    public const int WS_EX_TRANSPARENT = 0x00000020;
    public const int WS_EX_LAYERED = 0x00080000;

    [StructLayout(LayoutKind.Sequential)]
    public struct Size
    {
        public Int32 cx;
        public Int32 cy;

        public Size(Int32 x, Int32 y)
        {
            cx = x;
            cy = y;
        }
    }

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct BLENDFUNCTION
    {
        public byte BlendOp;
        public byte BlendFlags;
        public byte SourceConstantAlpha;
        public byte AlphaFormat;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct Point
    {
        public Int32 x;
        public Int32 y;

        public Point(Int32 x, Int32 y)
        {
            this.x = x;
            this.y = y;
        }
    }

    public const byte AC_SRC_OVER = 0;
    public const Int32 ULW_ALPHA = 2;
    public const byte AC_SRC_ALPHA = 1;

    /// <summary>
    /// 从左到右显示
    /// </summary>
    public const Int32 AW_HOR_POSITIVE = 0x00000001;
    /// <summary>
    /// 从右到左显示
    /// </summary>
    public const Int32 AW_HOR_NEGATIVE = 0x00000002;
    /// <summary>
    /// 从上到下显示
    /// </summary>
    public const Int32 AW_VER_POSITIVE = 0x00000004;
    /// <summary>
    /// 从下到上显示
    /// </summary>
    public const Int32 AW_VER_NEGATIVE = 0x00000008;
    /// <summary>
    /// 若使用了AW_HIDE标志,则使窗口向内重叠,即收缩窗口;否则使窗口向外扩展,即展开窗口
    /// </summary>
    public const Int32 AW_CENTER = 0x00000010;
    /// <summary>
    /// 隐藏窗口,缺省则显示窗口
    /// </summary>
    public const Int32 AW_HIDE = 0x00010000;
    /// <summary>
    /// 激活窗口。在使用了AW_HIDE标志后不能使用这个标志
    /// </summary>
    public const Int32 AW_ACTIVATE = 0x00020000;
    /// <summary>
    /// 使用滑动类型。缺省则为滚动动画类型。当使用AW_CENTER标志时,这个标志就被忽略
    /// </summary>
    public const Int32 AW_SLIDE = 0x00040000;
    /// <summary>
    /// 透明度从高到低
    /// </summary>
    public const Int32 AW_BLEND = 0x00080000;

    /// <summary>
    /// 执行动画
    /// </summary>
    /// <param name="whnd">控件句柄</param>
    /// <param name="dwtime">动画时间</param>
    /// <param name="dwflag">动画组合名称</param>
    /// <returns>bool值,动画是否成功</returns>
    [DllImport("user32")]
    public static extern bool AnimateWindow(IntPtr whnd, int dwtime, int dwflag);

    /// <summary>
    /// <para>该函数将指定的消息发送到一个或多个窗口。</para>
    /// <para>此函数为指定的窗口调用窗口程序直到窗口程序处理完消息再返回。</para>
    /// <para>而函数PostMessage不同,将一个消息寄送到一个线程的消息队列后立即返回。</para>
    /// return 返回值 : 指定消息处理的结果,依赖于所发送的消息。
    /// </summary>
    /// <param name="hWnd">要接收消息的那个窗口的句柄</param>
    /// <param name="Msg">消息的标识符</param>
    /// <param name="wParam">具体取决于消息</param>
    /// <param name="lParam">具体取决于消息</param>
    [DllImport("User32.dll", CharSet = CharSet.Auto, EntryPoint = "SendMessageA")]
    public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);

    [DllImport("user32.dll")]
    public static extern bool ReleaseCapture();

    [DllImport("user32")]
    public static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo); 

    [DllImport("gdi32.dll")]
    public static extern int CreateRoundRectRgn(int x1, int y1, int x2, int y2, int x3, int y3);

    [DllImport("user32.dll")]
    public static extern int SetWindowRgn(IntPtr hwnd, int hRgn, Boolean bRedraw);

    [DllImport("user32", EntryPoint = "GetWindowLong")]
    public static extern int GetWindowLong(
        IntPtr hwnd, int nIndex);

    [DllImport("user32.dll")]
    public static extern int SetWindowLong(
        IntPtr hwnd, int nIndex, int dwNewLong);

    [DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)]
    public static extern IntPtr CreateCompatibleDC(IntPtr hDC);

    [DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]
    public static extern IntPtr GetDC(IntPtr hWnd);

    [DllImport("gdi32.dll", ExactSpelling = true)]
    public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObj);

    [DllImport("user32.dll", ExactSpelling = true)]
    public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);

    [DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)]
    public static extern int DeleteDC(IntPtr hDC);

    [DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)]
    public static extern int DeleteObject(IntPtr hObj);

    [DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]
    public static extern int UpdateLayeredWindow(IntPtr hwnd, IntPtr hdcDst, ref Point pptDst, ref Size psize, IntPtr hdcSrc, ref Point pptSrc, Int32 crKey, ref BLENDFUNCTION pblend, Int32 dwFlags);

    [DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)]
    public static extern IntPtr ExtCreateRegion(IntPtr lpXform, uint nCount, IntPtr rgnData);



    /// <summary>
    /// 设置控件的圆角矩形
    /// </summary>
    public static void SetCtrlRoundRectRgn(IntPtr handel, int width, int height, int rgnRadius)
    {
        int hRgn = 0;
        hRgn = CreateRoundRectRgn(0, 0, width + 1, height + 1, rgnRadius, rgnRadius);
        SetWindowRgn(handel, hRgn, true);
        DeleteObject((IntPtr)hRgn);
    }

    /// <summary>
    /// 设置pnl控件的圆角
    /// </summary>
    /// <param name="pnl"></param>
    /// <param name="rgnRadius"></param>
    public static void SetPnlRoundRectRgn(Panel pnl, int rgnRadius = 17)
    {
        SetCtrlRoundRectRgn(pnl.Handle, pnl.Width, pnl.Height, rgnRadius);
    }
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
public void SetBits() { //绘制绘图层背景 Bitmap bitmap = new Bitmap(Main.Width + 10, Main.Height + 10); Rectangle _BacklightLTRB = new Rectangle(20, 20, 20, 20);//窗体光泽重绘边界 Graphics g = Graphics.FromImage(bitmap); g.SmoothingMode = SmoothingMode.HighQuality; //高质量 g.PixelOffsetMode = PixelOffsetMode.HighQuality; //高像素偏移质量 ImageDrawRect.DrawRect(g, Properties.Resources.main_light_bkg_top123, ClientRectangle, Rectangle.FromLTRB(_BacklightLTRB.X, _BacklightLTRB.Y, _BacklightLTRB.Width, _BacklightLTRB.Height), 1, 1); if (!Bitmap.IsCanonicalPixelFormat(bitmap.PixelFormat) || !Bitmap.IsAlphaPixelFormat(bitmap.PixelFormat)) throw new ApplicationException("图片必须是32位带Alhpa通道的图片。"); IntPtr oldBits = IntPtr.Zero; IntPtr screenDC = Win32.GetDC(IntPtr.Zero); IntPtr hBitmap = IntPtr.Zero; IntPtr memDc = Win32.CreateCompatibleDC(screenDC); try { Win32.Point topLoc = new Win32.Point(Left, Top); Win32.Size bitMapSize = new Win32.Size(Width, Height); Win32.BLENDFUNCTION blendFunc = new Win32.BLENDFUNCTION(); Win32.Point srcLoc = new Win32.Point(0, 0); hBitmap = bitmap.GetHbitmap(Color.FromArgb(0)); oldBits = Win32.SelectObject(memDc, hBitmap); blendFunc.BlendOp = Win32.AC_SRC_OVER; blendFunc.SourceConstantAlpha = Byte.Parse("255"); blendFunc.AlphaFormat = Win32.AC_SRC_ALPHA; blendFunc.BlendFlags = 0; Win32.UpdateLayeredWindow(Handle, screenDC, ref topLoc, ref bitMapSize, memDc, ref srcLoc, 0, ref blendFunc, Win32.ULW_ALPHA); } finally { if (hBitmap != IntPtr.Zero) { Win32.SelectObject(memDc, oldBits); Win32.DeleteObject(hBitmap); } Win32.ReleaseDC(IntPtr.Zero, screenDC); Win32.DeleteDC(memDc); } }
Winform圆角窗体可以通过自定义类和继承实现。具体步骤如下: 1. 创建项目,添加自定义类:MyWin32.cs和PerPixelAlphaBlend.cs;圆角窗体RoundedForm ;继承RoundedForm的窗体Form1。 2. 在MyWin32.cs中添加以下代码: ```csharp using System; using System.Runtime.InteropServices; namespace Win32 { public static class MyWin32 { [DllImport("user32.dll")] public static extern IntPtr GetDC(IntPtr hWnd); [DllImport("user32.dll")] public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC); [DllImport("gdi32.dll")] public static extern IntPtr CreateCompatibleDC(IntPtr hDC); [DllImport("gdi32.dll")] public static extern int DeleteDC(IntPtr hDC); [DllImport("gdi32.dll")] public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject); [DllImport("gdi32.dll")] public static extern int DeleteObject(IntPtr hObject); [DllImport("user32.dll")] public static extern int GetWindowRect(IntPtr hWnd, out RECT lpRect); [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left; public int Top; public int Right; public int Bottom; } } } ``` 3. 在PerPixelAlphaBlend.cs中添加以下代码: ```csharp using System; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; namespace Win32 { public static class PerPixelAlphaBlend { [DllImport("user32.dll")] public static extern IntPtr GetDC(IntPtr hWnd); [DllImport("user32.dll")] public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC); [DllImport("gdi32.dll")] public static extern IntPtr CreateCompatibleDC(IntPtr hDC); [DllImport("gdi32.dll")] public static extern int DeleteDC(IntPtr hDC); [DllImport("gdi32.dll")] public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject); [DllImport("gdi32.dll")] public static extern int DeleteObject(IntPtr hObject); [DllImport("msimg32.dll", EntryPoint = "AlphaBlend")] public static extern bool AlphaBlend(IntPtr hdcDest, int nXOriginDest, int nYOriginDest, int nWidthDest, int nHeightDest, IntPtr hdcSrc, int nXOriginSrc, int nYOriginSrc, int nWidthSrc, int nHeightSrc, BLENDFUNCTION blendFunction); [StructLayout(LayoutKind.Sequential)] public struct BLENDFUNCTION { public byte BlendOp; public byte BlendFlags; public byte SourceConstantAlpha; public byte AlphaFormat; } public static void SetBitmap(Bitmap bitmap, Control control) { SetBitmap(bitmap, control, 255); } public static void SetBitmap(Bitmap bitmap, Control control, byte opacity) { if (control == null) { throw new ArgumentNullException("control"); } IntPtr screenDc = GetDC(IntPtr.Zero); IntPtr memDc = CreateCompatibleDC(screenDc); IntPtr hBitmap = IntPtr.Zero; IntPtr oldBitmap = IntPtr.Zero; try { hBitmap = bitmap.GetHbitmap(Color.FromArgb(0)); oldBitmap = SelectObject(memDc, hBitmap); Size size = new Size(bitmap.Width, bitmap.Height); Point pointSource = new Point(0, 0); Point topPos = new Point(control.Left, control.Top); Win32.MyWin32.BLENDFUNCTION blend = new Win32.MyWin32.BLENDFUNCTION(); blend.BlendOp = 0; blend.BlendFlags = 0; blend.SourceConstantAlpha = opacity; blend.AlphaFormat = 1; Win32.MyWin32.RECT sourceRect = new Win32.MyWin32.RECT() { Left = pointSource.X, Top = pointSource.Y, Right = pointSource.X + size.Width, Bottom = pointSource.Y + size.Height }; Win32.MyWin32.RECT destRect = new Win32.MyWin32.RECT() { Left = topPos.X, Top = topPos.Y, Right = topPos.X + size.Width, Bottom = topPos.Y + size.Height }; IntPtr screenDc2 = GetDC(IntPtr.Zero); AlphaBlend(screenDc2, destRect.Left, destRect.Top, destRect.Right - destRect.Left, destRect.Bottom - destRect.Top, memDc, sourceRect.Left, sourceRect.Top, sourceRect.Right - sourceRect.Left, sourceRect.Bottom - sourceRect.Top, blend); ReleaseDC(IntPtr.Zero, screenDc2); } finally { SelectObject(memDc, oldBitmap); DeleteObject(hBitmap); DeleteDC(memDc); ReleaseDC(IntPtr.Zero, screenDc); } } } } ``` 4. 在RoundedForm.cs中添加以下代码: ```csharp using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace Win32 { public class RoundedForm : Form { private int radius = 20; public int Radius { get { return radius; } set { radius = value; } } protected override void OnPaint(PaintEventArgs e) { GraphicsPath path = GetRoundPath(ClientRectangle, radius); this.Region = new Region(path); e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; e.Graphics.FillPath(new SolidBrush(Color.White), path); } private GraphicsPath GetRoundPath(RectangleF rect, int radius) { float r2 = radius / 2f; GraphicsPath path = new GraphicsPath(); path.AddArc(rect.X, rect.Y, radius, radius, 180, 90); path.AddLine(rect.X + r2, rect.Y, rect.Width - r2, rect.Y); path.AddArc(rect.X + rect.Width - radius, rect.Y, radius, radius, 270, 90); path.AddLine(rect.Width, rect.Y + r2, rect.Width, rect.Height - r2); path.AddArc(rect.X + rect.Width - radius, rect.Y + rect.Height - radius, radius, radius, 0, 90); path.AddLine(rect.Width - r2, rect.Height, rect.X + r2, rect.Height); path.AddArc(rect.X, rect.Y + rect.Height - radius, radius, radius, 90, 90); path.AddLine(rect.X, rect.Height - r2, rect.X, rect.Y + r2); path.CloseFigure(); return path; } } } ``` 5. 在Form1.cs中继承RoundedForm,并添加以下代码: ```csharp public partial class Form1 : RoundedForm { public Form1() { InitializeComponent(); this.Radius = 20; } } ``` 6. 在Form1.Designer.cs中添加以下代码: ```csharp this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(284, 261); this.Name = "Form1"; this.Text = "Form1"; ``` 7. 在Form1_Load事件中添加以下代码: ```csharp private void Form1_Load(object sender, EventArgs e) { this.BackColor = Color.FromArgb(0, 0, 0, 0); PerPixelAlphaBlend.SetBitmap(Properties.Resources.background, this); } ``` 其中,background是一个png格式的图片,用于设置窗体背景。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值