从头开始创建可移动控件

时间:2012-03-22 01:46:00

标签: c# winforms window location position

我必须让用户控制你可以移动它,但我必须从头开始(即获取控件的位置并计算鼠标移动时的差异并相应地移动控件) 这就是我现在所拥有的。

public partial class MainMenu:UserControl {     public Point OldMouseLoc;     public Point OldWindowLoc;     public MainMenu()     {         的InitializeComponent();     }

private void customButton1_MouseDown(object sender, MouseEventArgs e)
{
    OldMouseLoc = MousePosition;
    OldWindowLoc = new Point(this.Location.X + this.Parent.Location.X,this.Location.Y + this.Parent.Location.Y);
    Mover.Start();
}

private void Mover_Tick(object sender, EventArgs e)
{
    Point NewMouseLoc = MousePosition;
    if (NewMouseLoc.X > OldMouseLoc.X || true) { // ( || true is for debugging)
        this.Location = new Point(NewMouseLoc.X - OldWindowLoc.X, this.Location.Y);
        MessageBox.Show(NewMouseLoc.X.ToString() + "   " + OldWindowLoc.X.ToString()); // for debugging
    }
}

}

现在我遇到麻烦的原因是因为MousePosition是相对于屏幕顶部的,而我的控件位置是相对于其父窗口的左上角。弄清楚所有东西的坐标的数学让我头疼,请只修复这些的X位置,这样我就可以用它来弄清Y(所以我可以学习如何自己)。

1 个答案:

答案 0 :(得分:2)

PointToClient应该为你做数学运算。您需要在控件的父级上调用此方法。

<强>更新

还要考虑稍微不同的方法。你真的不需要任何计时器或屏幕坐标:

    private Point _mdLocation;

    private void customButton1_MouseDown(object sender, MouseEventArgs e)
    {
        _mdLocation = e.Location;
    }

    private void customButton1_MouseMove(object sender, MouseEventArgs e)
    {
        if(e.Button == MouseButtons.Left)
        {
            var x = this.Left + e.X - _mdLocation.X;
            var y = this.Top + e.Y - _mdLocation.Y;
            this.Location = new Point(x, y);
        }
    }