C# - 移动控制鼠标的位置 [英] C# - Moving a control to the mouse's position

查看:370
本文介绍了C# - 移动控制鼠标的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想拿到的一个控件跟随光标当用户点击并拖动控制。问题是,1)控制不走鼠标的位置,和2)控制闪烁飞得到处都是。我已经试过这样做的几种不同的方法,但都至今都未能

I am trying to get a control to follow the cursor when the user clicks and drag the control. The problem is that 1.) the control doesn't go to the mouse's position, and 2.) the control flickers and flies all over the place. I've tried a few different methods of doing this, but all so far have failed.

我试过:

protected override void OnMouseDown(MouseEventArgs e)
{
     while (e.Button == System.Windows.Forms.MouseButtons.Left)
     {
          this.Location = e.Location;
     }
}

protected override void OnMouseMove(MouseEventArgs e)
{
     while (e.Button == System.Windows.Forms.MouseButtons.Left)
     {
          this.Location = e.Location;
      }
}



但这些都不工作。 !任何帮助表示赞赏,并提前感谢

but neither of these work. Any help is appreciated, and thanks in advance!

推荐答案

下面是如何做到这一点:

Here's how to do it:

private Point _Offset = Point.Empty;

protected override void MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        _Offset = new Point(e.X, e.Y);
    }
}

protected override void MouseMove(object sender, MouseEventArgs e)
{
    if (_Offset != Point.Empty)
    {
        Point newlocation = this.Location;
        newlocation.X += e.X - _Offset.X;
        newlocation.Y += e.Y - _Offset.Y;
        this.Location = newlocation; 
    }
}

protected override void MouseUp(object sender, MouseEventArgs e)
{
    _Offset = Point.Empty;
}



_Offset 使用这里有两个目的:保持跟踪,其中鼠标是上的控制,当你最初点击它,并且还跟踪的鼠标键是否关闭或没有(这样,当鼠标指针越过控制没有得到拖它和按钮不下来)。

_Offset is used here for two purposes: keeping track of where the mouse was on the control when you initially clicked it, and also keeping track of whether the mouse button is down or not (so that the control doesn't get dragged when the mouse cursor goes over it and the button isn't down).

您绝对的的希望切换如果 S IN此代码,而 S,因为它的将会的有所作为。

You definitely don't want to switch the ifs in this code to whiles, as it will make a difference.

这篇关于C# - 移动控制鼠标的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆