Oztaco
Oztaco

Reputation: 3459

Creating a moveable control out of scratch

I have to make a user control where you can move it, but i have to make it out of scratch (ie get the position of the control and calculating the difference as the mouse is moved and moving the control accordingly) this is what i have now.

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
    }
}

}

Now the reason Im having trouble is because MousePosition is relative to the top of the screen, while my controls location is relative to the top left of its parent window. The math to figure out the coordinates for everything is giving me a huge headache, please only fix the X position of these so I can use that to figure out the Y's (so i can learn how to myself).

Upvotes: 1

Views: 122

Answers (1)

max
max

Reputation: 34407

PointToClient should do that math for you. You need to call this method on parent of your control.

Update:

Also consider slightly different approach. You don't really need any timers or screen coordinates:

    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);
        }
    }

Upvotes: 2

Related Questions