C#中,在一个按钮上按下鼠标左键然后移动,整个窗体跟着光标移动,如何实现?恳请高手指点,谢谢!
2个回答
展开全部
bool isMouseDown = false;
Point mouseOffset;
先添加全局变量
再添加下面这几个事件
private void TableLrcF_MouseMove(object sender, MouseEventArgs e)
{
if (isMouseDown)
{
Point mousePos = Control.MousePosition;
mousePos.Offset(mouseOffset.X, mouseOffset.Y);
Location = mousePos;
}
}
private void TableLrcF_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
mouseOffset = new Point(-e.X, -e.Y);
isMouseDown = true;
}
}
private void TableLrcF_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isMouseDown = false;
}
}
Point mouseOffset;
先添加全局变量
再添加下面这几个事件
private void TableLrcF_MouseMove(object sender, MouseEventArgs e)
{
if (isMouseDown)
{
Point mousePos = Control.MousePosition;
mousePos.Offset(mouseOffset.X, mouseOffset.Y);
Location = mousePos;
}
}
private void TableLrcF_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
mouseOffset = new Point(-e.X, -e.Y);
isMouseDown = true;
}
}
private void TableLrcF_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isMouseDown = false;
}
}
追问
请问这个函数的作用是什么:mousePos.Offset(mouseOffset.X, mouseOffset.Y);
这句怎么解释:mouseOffset = new Point(-e.X, -e.Y);为何参数为负?
移动时鼠标会自动跳到标题栏啊,能不能再完善点?想它还留在按钮上啊。
请解释,谢谢!
追答
mousePos.Offset(mouseOffset.X, mouseOffset.Y)是将mousePos平移指定的量
不好意思,你说要在按钮上做窗体拖动事件就不能用上面的代码了,应为按钮的点击事件没有相应的坐标信息,但还是有办法的,看代码:
bool beginMove = false;
int currentXPosition = 0;
int currentYPosition = 0;
private void Button_MouseDown(object sender, MouseEventArgs e)
{
beginMove = true;
currentXPosition = MousePosition.X;
currentYPosition = MousePosition.Y;
}
private void Button_MouseMove(object sender, MouseEventArgs e)
{
if (beginMove)
{
this.Left += MousePosition.X - currentXPosition;
this.Top += MousePosition.Y - currentYPosition;
currentXPosition = MousePosition.X;
currentYPosition = MousePosition.Y;
}
}
private void Button_MouseUp(object sender, MouseEventArgs e)
{
beginMove = false;
}
其实这个方法才是万能的,这个应该看得懂吧,还看不懂我会自杀的,呵呵
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询