dave_bulac
dave_bulac

Reputation: 45

How to get coordinates of a Mouse when it's Clicked

I'm beginner in c# and need some help. After loading Form I want to display on Form coordinates of a Mouse when it's Clicked. Click can be made outside of the Form. For example in Browser. Can someone help me with this.

Upvotes: 0

Views: 5113

Answers (4)

Reza Aghaei
Reza Aghaei

Reputation: 125177

Maybe the most simple way is setting Capture property of a form to true, then handle click event and convert the position (that is position related to top left point of form) to screen position using PointToScreen method of form.

For example you can put a button on form and do:

private void button1_Click(object sender, EventArgs e)
{
    //Key Point to handle mouse events outside the form
    this.Capture = true;
}

private void MouseCaptureForm_MouseDown(object sender, MouseEventArgs e)
{
    this.Activate();    
    MessageBox.Show(this.PointToScreen(new Point(e.X, e.Y)).ToString());

    //Cursor.Position works too as RexGrammer stated in his answer
    //MessageBox.Show(this.PointToScreen(Cursor.Position).ToString());

    //if you want form continue getting capture, Set this.Capture = true again here
    //this.Capture = true;
    //but all clicks are handled by form now 
    //and even for closing application you should
    //right click on task-bar icon and choose close.
}

But more correct (and slightly difficult) way is using global hooks.
If you really need to do it, you can take a look at this links:

Upvotes: 1

Jehonathan Thomas
Jehonathan Thomas

Reputation: 2200

You need a global mouse hook.

See this question

Upvotes: 0

matteeyah
matteeyah

Reputation: 875

Cursor.Position and Control.MousePosition both return the position of the mouse cursor in screen coordinates.

The following articles deal with capturing Global mouse click events:

Processing Global Mouse and Keyboard Hooks in C#
Global Windows Hooks

Upvotes: 0

Mohammad Chamanpara
Mohammad Chamanpara

Reputation: 2159

I think you can't handle the mouse click outside your Form at least easily. inside the form using MouseEventArgs it can simply be handled.

private void Form1_MouseClick(object sender, MouseEventArgs e)
{
     // e.Location.X & e.Location.Y
}

Learn more about this topic at Mouse Events in Windows Forms.

I hope it helps.

Upvotes: 0

Related Questions