Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Position of mouse cursor when clicked out side the form's boundary

It is very easy to get the position of cursor out side the form's boundary by just dragaging the mouse it sends many values to the form when ever the position changes, form the following line of code.

MessageBox.Show(Cursor.Position.ToString());

MessageBox showing mouse position.

But I need to get the mouse position when user clicked out side the forms boundary. Not by just hovering the mouse. I used the following line of Code to do this:

private void Form1_Deactivate(object sender, EventArgs e)
{
    MessageBox.Show(Cursor.Position.ToString());
}

I placed MessageBox.Show(Cursor.Position.ToString()); into forms Deactivate event. When user click outside the form this event definitely occures. But it also sends wrong values when user does not click outside but changes the program by using ALT + TAB key combination.

Actually I have to capture screen shot of the area starting from the position of first click. Therefore I need the position of the cursor when it is clicked outside the form. like: enter image description here

like image 951
Farid-ur-Rahman Avatar asked Apr 03 '11 08:04

Farid-ur-Rahman


2 Answers

This might help some one.

Here I am using Windows.Forms.Timer and two text boxes for displaying [X and Y] cursor positions. On timer tick calling the API GetCursorPos and getting the cursor position.

public partial class Form1 : Form
{
    [DllImport("user32.dll")]
    static extern bool GetCursorPos(ref Point lpPoint);

    public Form1()
    {
        InitializeComponent();
        timer1.Start();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        var pt = new Point();

        GetCursorPos(ref pt);
        textBox1.Text = pt.X.ToString();
        textBox2.Text = pt.Y.ToString();
    }   
}

Regards, Ranjeet.

like image 130
Ranjeet Avatar answered Sep 23 '22 11:09

Ranjeet


You should use Global Mouse Hook logic to do this.

Here is a good article that will help you: Processing Global Mouse and Keyboard Hooks in C#

like image 32
HABJAN Avatar answered Sep 22 '22 11:09

HABJAN