在使用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(); }
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; } }