110,539
社区成员
发帖
与我相关
我的任务
分享
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
PictureBox pic;
Point beginPoint;
Point endPoint;
private void button1_Click(object sender, EventArgs e)
{
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
pic = new PictureBox();
beginPoint = new Point(e.X, e.Y);
pic.Location = beginPoint;
pic.BackColor = Color.Red;
pictureBox1.Controls.Add(pic);
//pic.BringToFront();
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
//先删除动态添加的pic,然后在picturebox1上画直线
pictureBox1.Controls.Remove(pic);
using (Graphics g = pictureBox1.CreateGraphics())
{
g.DrawLine(new Pen(Color.Black, 2), beginPoint, new Point(e.X, e.Y));
}
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left && pic != null)
{
pic.Width = e.X - beginPoint.X - 10;
pic.Height = e.Y - beginPoint.Y - 10;
using (Graphics g = pic.CreateGraphics())
{
if (endPoint != null)
{
//用背景色画线,覆盖掉上次画的线
g.DrawLine(new Pen(pic.BackColor, 2), new Point(0, 0), new Point(endPoint.X - beginPoint.X - 10, endPoint.Y - beginPoint.Y - 10));
}
g.DrawLine(new Pen(Color.Black, 2), new Point(0, 0), new Point(e.X - beginPoint.X - 10, e.Y - beginPoint.Y - 10));
}
endPoint = new Point(e.X, e.Y);
}
}
}
public partial class Form1 : Form
{
private Point ptDown = Point.Empty;
private Point ptCurrent = Point.Empty;
private bool isMouseDown = false;
private List<LineObj> lines = new List<LineObj>();
public Form1()
{
InitializeComponent();
this.DoubleBuffered = true;
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
ptDown = e.Location;
isMouseDown = true;
this.Focus();
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
if (isMouseDown)
{
var obj = new LineObj() { Start = ptDown, End = e.Location };
lines.Add(obj);
isMouseDown = false;
}
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (isMouseDown)
{
ptCurrent = e.Location;
this.Invalidate();
}
}
//取消添加
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if(e.KeyCode == Keys.Escape)
{
isMouseDown = false;
this.Invalidate();
}
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
foreach(var obj in lines)
{
e.Graphics.DrawLine(Pens.Black, obj.Start, obj.End);
}
if (isMouseDown)
{
e.Graphics.DrawLine(Pens.Black, ptDown, ptCurrent);
}
}
}
internal class LineObj
{
public Point Start { get; set; }
public Point End { get; set; }
}