Viva
Viva

Reputation: 2075

get cursor position

I have an usercontrol called TaskControl and a button for creating other usercontrols by dragging. I want the new user control that appears to be at the same coordinates where my cursor is. Below it is my code. It doesn't want to appear at those coordinates and the new usercontrol appears behind the old one. My code:

 private void button1_Click(object sender, EventArgs e)
    {


        Point localCoordinates = this.PointToClient(Cursor.Position);
        TaskControl t = new TaskControl();
        t.Location = new Point(Cursor.Position.X,Cursor.Position.Y);
        t.MouseDown += new MouseEventHandler(t_MouseDown);
        t.MouseMove += new MouseEventHandler(t_MouseMove);
        t.MouseUp += new MouseEventHandler(t_MouseUp);

        this.Controls.Add(t);
    } 

Upvotes: 1

Views: 350

Answers (2)

Soner Gönül
Soner Gönül

Reputation: 98750

Take a look Control.MousePosition

Gets the position of the mouse cursor in screen coordinates.

Upvotes: 1

Tigran
Tigran

Reputation: 62246

You have to work out that using Control.MousePosition static property, which

Gets the position of the mouse cursor in screen coordinates.

After move your use control to the coordinates retrived. Please note, that depends on how you architect your UI, you may need to convert coordinates to client. For this can use Control.PointToClient static method, which:

Computes the location of the specified screen point into client coordinates.

Upvotes: 1

Related Questions