C# 在windows form窗体中,如果任意拖一个控件,鼠标点击它后,能够随着鼠标移动。 程序编写?
2个回答
展开全部
所有的控件都加上这三个事件:
#region 移动相关
bool _moving = false;
Point _offset;
private void _MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
return;
_moving = true;
_offset = new Point(Control.MousePosition.X - ((Control)sender).Location.X, Control.MousePosition.Y - ((Control)sender).Location.Y);
}
private void _MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
return;
if (_moving)
((Control)sender).Location = new Point(Control.MousePosition.X - _offset.X, Control.MousePosition.Y - _offset.Y);
}
private void _MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
return;
_moving = false;
}
#endregion
#region 移动相关
bool _moving = false;
Point _offset;
private void _MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
return;
_moving = true;
_offset = new Point(Control.MousePosition.X - ((Control)sender).Location.X, Control.MousePosition.Y - ((Control)sender).Location.Y);
}
private void _MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
return;
if (_moving)
((Control)sender).Location = new Point(Control.MousePosition.X - _offset.X, Control.MousePosition.Y - _offset.Y);
}
private void _MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
return;
_moving = false;
}
#endregion
2011-03-21
展开全部
bool flag; Point mp, bp; Timer t;
private void button1_Click(object sender, EventArgs e)
{
t = new Timer();
bp = this.button1.Location;
mp = Cursor.Position;
flag = true; t.Start();
t.Interval = 100; t.Tick += new EventHandler(t_Tick);
}
void t_Tick(object sender, EventArgs e)
{
Point mp1 = Cursor.Position;
int x = mp1.X - mp.X;
int y = mp1.Y - mp.Y;
this.button1.Location = new Point(bp.X + x, bp.Y + y);
if (flag) { if (x == 0 && y == 0)return; }
}
缺点:点击按钮无法停下,你在看看办法
private void button1_Click(object sender, EventArgs e)
{
t = new Timer();
bp = this.button1.Location;
mp = Cursor.Position;
flag = true; t.Start();
t.Interval = 100; t.Tick += new EventHandler(t_Tick);
}
void t_Tick(object sender, EventArgs e)
{
Point mp1 = Cursor.Position;
int x = mp1.X - mp.X;
int y = mp1.Y - mp.Y;
this.button1.Location = new Point(bp.X + x, bp.Y + y);
if (flag) { if (x == 0 && y == 0)return; }
}
缺点:点击按钮无法停下,你在看看办法
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询