1、文件结构
2、控件视图
3、程序代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UserCtrlLib
{
public partial class LatchPower : UserControl
{
public LatchPower()
{
InitializeComponent();
RoundRadius = 10;
}
#region Properties
private int roundRadius;
[Description("圆角半径(0为不要圆角)")]
[Category("自定义外观")]
public int RoundRadius
{
get { return roundRadius; }
set
{
if(value < 0)
{
roundRadius = 0;
}
else
{
roundRadius = value;
}
base.Refresh();
}
}
#endregion
#region Override Methods
/// <summary>
/// 在控件尺寸变化时刷新
/// </summary>
/// <param name="e"></param>
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
base.Refresh();
}
/// <summary>
/// 将控件边框修改成圆角
/// </summary>
/// <param name="e"></param>
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Round(this.Region, RoundRadius);
}
#endregion
#region UI Methods
/// <summary>
/// 绘制控件的圆角
/// </summary>
/// <param name="region"></param>
/// <param name="radius"></param>
public void Round(System.Drawing.Region region, int radius)
{
System.Drawing.Drawing2D.GraphicsPath oPath = new System.Drawing.Drawing2D.GraphicsPath();
int x = 0;
int y = 0;
int thisWidth = this.Width;
int thisHeight = this.Height;
int angle = radius;
// 半径非0为圆角矩形
if (angle > 0)
{
System.Drawing.Graphics g = CreateGraphics();
oPath.AddArc(x, y, angle, angle, 180, 90); // 左上角
oPath.AddArc(thisWidth - angle, y, angle, angle, 270, 90); // 右上角
oPath.AddArc(thisWidth - angle, thisHeight - angle, angle, angle, 0, 90); // 右下角
oPath.AddArc(x, thisHeight - angle, angle, angle, 90, 90); // 左下角
oPath.CloseAllFigures();
Region = new System.Drawing.Region(oPath);
}
//半径为0时为矩形
else
{
angle = 0;
oPath.AddLine(x + angle, y, thisWidth - angle, y); // 顶端
oPath.AddLine(thisWidth, y + angle, thisWidth, thisHeight - angle); // 右边
oPath.AddLine(thisWidth - angle, thisHeight, x + angle, thisHeight); // 底边
oPath.AddLine(x, y + angle, x, thisHeight - angle); // 左边
oPath.CloseAllFigures();
Region = new System.Drawing.Region(oPath);
}
}
#endregion
}
}
4、调用并运行