|
|
发表于 2023-10-18 16:29:25
|
显示全部楼层
广西壮族自治区南宁市
public partial class MainForm : Form
{
private bool isDrawing;
private Point startPoint;
private Point endPoint;
public MainForm()
{
InitializeComponent();
// 添加鼠标按下和松开事件处理程序
this.MouseDown += MainForm_MouseDown;
this.MouseUp += MainForm_MouseUp;
// 添加鼠标移动事件处理程序
this.MouseMove += MainForm_MouseMove;
// 设置双缓冲,以减少绘制的闪烁
this.DoubleBuffered = true;
}
private void MainForm_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isDrawing = true;
startPoint = e.Location;
endPoint = e.Location;
this.Invalidate(); // 强制绘制
}
}
private void MainForm_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isDrawing = false;
endPoint = e.Location;
this.Invalidate(); // 强制绘制
}
}
private void MainForm_MouseMove(object sender, MouseEventArgs e)
{
if (isDrawing)
{
endPoint = e.Location;
this.Invalidate(); // 强制绘制
}
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
// 在启动窗口上绘制直线
if (isDrawing)
{
using (Pen pen = new Pen(Color.Black, 2))
{
e.Graphics.DrawLine(pen, startPoint, endPoint);
}
}
}
} |
|