当前位置:首页 > Windows程序 > 正文

c#无边框异形窗体制作

2021-05-24 Windows程序

下面是最终效果:

技术分享

 

技术分享

这就是一个无边框窗体 可以注意到它的外观 四个角是圆的 有控制按钮 并且还可以拖拽,,当鼠标移动到窗体的四个角和边缘的时候可以拖拽大小

这个窗体没有标题栏和边框的限制 控件可以放在窗体上任何地方

下面就是直奔主题了:

先说一说制作这个窗体的思路(窗体集成自System.Windows.Forms.Form):

1.设置FormBorderStyle属性为none 让它成为一个无边框窗体

2.设置窗体的Region属性 该属性设置窗体的有效区域 而我们把窗体的有效区域设置为圆角矩形 窗体就变成圆角的了

3.自定义控件 3个按钮 控制窗体的最大化 最小化 还原 关闭

4.使窗体可以拖动 在边缘按下鼠标可以拖拽大小

主要涉及GDI+中两个重要的类 Graphics和GraphicsPath类 分别位于System.Drawing和System.Drawing.Drawing2D

首先我们创建一个C# windows窗体应用程序项目 将默认的Form1改名成MainForm 设置FormBorderStyle属性为none 让它成为一个无边框窗体

接着我们需要这样一个函数 private void  SetWindowRegion() 此函数设置窗体有效区域为圆角矩形,以及一个辅助函数 private GraphicsPath GetRoundedRectPath(Rectangle rect, int radius)此函数用来创建圆角矩形路径,将在SetWindowRegion()中调用它

代码

public void SetWindowRegion() {     System.Drawing.Drawing2D.GraphicsPath FormPath;     FormPath = new System.Drawing.Drawing2D.GraphicsPath();     Rectangle rect = new Rectangle(00this.Width, this.Height);     FormPath = GetRoundedRectPath(rect, 10);     this.Region = new Region(FormPath);
} private GraphicsPath GetRoundedRectPath(Rectangle rect, int radius) {     int diameter = radius;     Rectangle arcRect = new Rectangle(rect.Location, new Size(diameter, diameter));     GraphicsPath path = new GraphicsPath();
    // 左上角     path.AddArc(arcRect, 18090);
    // 右上角     arcRect.X = rect.Right - diameter;     path.AddArc(arcRect, 27090);
    // 右下角     arcRect.Y = rect.Bottom - diameter;     path.AddArc(arcRect, 090);
    // 左下角     arcRect.X = rect.Left;     path.AddArc(arcRect, 9090);     path.CloseFigure();//闭合曲线     return path; }

在窗体尺寸改变的时候我们需要调用SetWindowRegion()将窗体变成圆角的

private void MainForm_Resize(object sender, EventArgs e) {     SetWindowRegion(); }

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/70183.html