C# Winform圆形窗体和圆形按钮

时间:2024-03-26 17:47:32

圆形窗体
找到窗体的Paint事件,写入以下代码:

 		private void form1_Paint(object sender, PaintEventArgs e)
        {
            #region 圆形窗体
            System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath();//创建一条线
            path.AddEllipse(0, 0, Width, Height);//画一个椭圆 (x,y,宽,高)
            Graphics g = CreateGraphics();//为窗体创建画布
            g.DrawEllipse(new Pen(Color.Black, 2), 1, 1, Width - 2, Height - 2);//为画布画一个椭圆(笔,x,y,宽,高)
            Region = new Region(path);//设置控件的窗口区域
            #endregion
        }

效果:
C# Winform圆形窗体和圆形按钮
圆形按钮代码:

    public class CircleButton : Button//继承按钮类    重新生成解决方案就能看见我啦
    {
        protected override void OnPaint(PaintEventArgs e)//重新设置控件的形状   protected 保护  override重新
        {
            base.OnPaint(e);//递归  每次重新都发生此方法,保证其形状为自定义形状
            System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath();
            path.AddEllipse(2, 2, this.Width - 6, this.Height - 6);
            Graphics g = e.Graphics;
            g.DrawEllipse(new Pen(Color.Black, 2), 2, 2, Width - 6, Height - 6);
            Region = new Region(path);
        }
    }

重新生成解决方案后工具箱出现我们的自定义按钮
C# Winform圆形窗体和圆形按钮
将他拖到界面上,效果:
C# Winform圆形窗体和圆形按钮