使用C#创建不规则窗体

在使用C#的学习过程中,发现窗体的样式是可以通过绘制来改变的,为了以后查找方便,故在此记录一下使用方法(以下流程在VS2008中测试通过)!

1. 使用VS2008创建一个C#的WinForm窗体程序

2. 将窗体中的FormBorderStyle设置为"None"

3. 将窗体的BackColor和TransparencyKey属性的Color颜色设置成一致

4. 选择一个图片作为程序的背景(图片可以是任意的,没有任何关系),并将图片命名为1.jpg

5. 重载窗体的OnPaint函数,并在下面编写如下代码(如果希望是其他形状的窗体外观,修改这里面的代码即可)

        protected override void OnPaint(PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            Rectangle mainRect = new Rectangle(0, 0, 695, 278);
            Region mainRegion = new Region(mainRect);
            e.Graphics.SetClip(mainRegion, CombineMode.Replace);
            
           //设置窗体的外观形式
            Point point1 = new Point(0, 32);
            Point point2 = new Point(9, 20);
            Point point3 = new Point(21, 13);
            Point point4 = new Point(34, 9);
            // 创建一个以点为元素的数组
            Point[] curvePoints = { point1, point2, point3, point4 };
            // 创建一个GraphicsPath 对象并添加一条曲线
            GraphicsPath gPath = new GraphicsPath();
            gPath.AddCurve(curvePoints, 0, 3, 0.8f);
            gPath.AddLine(36, 9, 378, 9);
            point1.X = 378; point1.Y = 9;
            point2.X = 387; point2.Y = 5;
            point3.X = 394; point3.Y = 0;
            Point[] curvePoints2 = { point1, point2, point3 };
            gPath.AddCurve(curvePoints2, 0, 2, 0.8f);
            gPath.AddLine(394, 0, 0, 0);
            Region rg = new Region(gPath);            
            e.Graphics.ExcludeClip(rg);

            string str = Directory.GetCurrentDirectory() + "\\1.jpg";
            Image img = Image.FromFile(str);
            e.Graphics.DrawImage(img, 0, 0, 695, 278);

            // 重设剪切好的区域
            e.Graphics.ResetClip();
        }

6. 此时的WinForm程序已经可以显示出不规则的样式了,但是窗体不能关闭,此时在程序的界面设计页中,将一个Button按钮添加到界面的右上角(Button名称设置为CloseForm),该Button没有设置Text属性,另外Button的Image属性设置为"X"(图片微软有现成的,直接用就可以),并添加如下代码

        private void CloseForm_Click(object sender, EventArgs e)
        {
            this.Close();
        }

7. 此时的WinForm程序已经可以显示出不规则的样式了,但是窗体不能移动,按照下面的方式进行处理后,窗体就可以移动了

        private Point form_pos;
    
        protected override void OnMouseDoubleClick(MouseEventArgs e)
        {
            form_pos = new Point(-e.X, -e.Y);
        }

        protected override void OnMouseMove(MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                Point mousePos = Control.MousePosition;
                form_pos.Offset(mouse_offset.X, mouse_offset.Y);
                Location = mousePos;
            }
        }

8. 编译运行,看看效果吧! Is so perfect!!!

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值