在C# 绘制一个可拖拽的圆型窗体,需要用到以下方法与属性
方法:
e.Graphics
对象来执行自定义绘图操作。属性:
None
以创建无边框窗体。GraphicsPath
结合使用。C#public partial class Form1 : Form
{
private Point offset; // 用于存储鼠标按下时的偏移量
private bool isDragging = false; // 用于跟踪是否正在拖动窗体
public Form1()
{
InitializeComponent();
this.FormBorderStyle = FormBorderStyle.None;
this.Opacity= 0.8;
this.DoubleBuffered = true; // 双缓冲以减少闪烁
// 鼠标按下事件处理
this.MouseDown += (sender, e) =>
{
if (e.Button == MouseButtons.Left)
{
offset = e.Location;
isDragging = true;
}
};
// 鼠标移动事件处理
this.MouseMove += (sender, e) =>
{
if (isDragging)
{
// 移动窗体到新位置
Point newLocation = this.Location;
newLocation.X += e.X - offset.X;
newLocation.Y += e.Y - offset.Y;
this.Location = newLocation;
}
};
// 鼠标释放事件处理
this.MouseUp += (sender, e) =>
{
if (e.Button == MouseButtons.Left)
{
isDragging = false;
}
};
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
GraphicsPath path = new GraphicsPath();
path.AddEllipse(0, 0, this.Width, this.Height);
// 设置窗体的Region为圆形区域
this.Region = new Region(path);
using (Pen borderPen = new Pen(Color.Red, 5)) // 定义边框宽度和颜色
{
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; // 启用抗锯齿
e.Graphics.DrawEllipse(borderPen, 2, 2, this.Width - 4, this.Height);ss
}
}
}
本文作者:技术老小子
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!