110,534
社区成员
发帖
与我相关
我的任务
分享
Point p = new Point(0, 0); //这个是测点,根据需要改
Rectangle rect = new Rectangle(10, 10, 50, 50);//浮动框的初始位置
bool _mousedown = false;//鼠标是否按下
int _x, _y;//初始x,y坐标
//自画事件,先画矩形,然后划一根线,和矩形的左下角相连
private void Form2_Paint(object sender, PaintEventArgs e)
{
e.Graphics.FillRectangle(Brushes.Red, this.rect);
e.Graphics.DrawLine(Pens.Red, this.p, new Point(this.rect.Left,this.rect.Bottom));
}
//以下是鼠标动作,当鼠标点在rect范围内时,有效,可以拖动
private void Form2_MouseDown(object sender, MouseEventArgs e)
{
if (this.rect.Contains(e.Location))
{
this._mousedown = true;
this._x = e.X;
this._y = e.Y;
}
}
private void Form2_MouseUp(object sender, MouseEventArgs e)
{
this._mousedown = false;
}
private void Form2_MouseMove(object sender, MouseEventArgs e)
{
if (!this._mousedown) return;
//重置拖动区域的位置
this.rect.Location = new Point(e.X - this._x,e.Y - this._y);
this.Invalidate();
}