码迷,mamicode.com
首页 > Windows程序 > 详细

C# 开发圆角窗体

时间:2017-03-18 13:48:50      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:c#   drawing   圆角窗体   按钮   透明   

   因为项目需要做个Winform的随机启动的数据上传工具,用Visual Studio的窗体感觉太丑了,就想进行优化,反正就一个窗体,上面也没啥按钮,就不要标题栏了,就搞一个圆角的窗体好了,搞个漂亮的背景图片。上面搞一个最小化和关闭按钮。把窗体设置为圆角窗口的操作如下:

    1、把窗体frmMain的FormBorderStyle属性设置为None,去掉窗体的边框,让窗体成为无边框的窗体。

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

    3、添加两个控件,控制窗体的最小化和关闭。

    设置为圆角窗体,主要涉及GDI+中两个重要的类 Graphics和GraphicsPath类,分别位于System.Drawing和System.Drawing.Drawing2D。

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

ublic void SetWindowRegion()  
{  
    System.Drawing.Drawing2D.GraphicsPath FormPath;  
    FormPath = new System.Drawing.Drawing2D.GraphicsPath();  
    Rectangle rect = new Rectangle(0, 0, this.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, 180, 90);    
    // 右上角  
    arcRect.X = rect.Right - diameter;  
    path.AddArc(arcRect, 270, 90);    
    // 右下角  
    arcRect.Y = rect.Bottom - diameter;  
    path.AddArc(arcRect, 0, 90);    
    // 左下角  
    arcRect.X = rect.Left;  
    path.AddArc(arcRect, 90, 90);  
    path.CloseFigure();//闭合曲线  
    return path;  
}

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

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

设置按钮的形状:

   添加两个普通的按钮button,设置按钮的BackColor属性为Transparent,让背景透明,不然按钮的背景色与窗体的图片背景不相符。设置按钮的FlatStyle属性为Flat,同时设置FlatAppearance属性中的BorderSize=0,MouseDownBackColor和MouseOverBackColor的值均为Transparent,防止点击按钮时,颜色变化影响美观。调整按钮的大小和位置即可。最小化和关闭按钮(是右下角托盘,所以没有退出程序)的代码如下:

private void btn_min_Click(object sender, EventArgs e)
{
	this.WindowState = FormWindowState.Minimized;
}
private void btn_close_Click(object sender, EventArgs e)
{
	this.WindowState = FormWindowState.Minimized;
	this.Hide();
}

  还可以添加代码,控制鼠标移动到操作按钮上时,改变按钮上文字的颜色,来增加体验。

程序界面如下图

技术分享

本文出自 “为何一笑” 博客,请务必保留此出处http://helicon.blog.51cto.com/3926609/1907838

C# 开发圆角窗体

标签:c#   drawing   圆角窗体   按钮   透明   

原文地址:http://helicon.blog.51cto.com/3926609/1907838

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!