Saif Ali Khan
Saif Ali Khan

Reputation: 55

Detect mouse clicks outside the form C#

i'm a newbie in c#. I want to track mouse clicks outside the form. Tried mousekeyhook, but don't really know which snippet of code will go where. Thanks in advance.

 public partial class Form1 : Form
        {
            public string label2Y;
            public string label1X;
            public Form1()
            {
                InitializeComponent();
            }

            private void Form1_MouseMove(object sender, MouseEventArgs e)
            {
                label1.Text = Cursor.Position.X.ToString();
                label2.Text = Cursor.Position.Y.ToString();
            }

            private void Form1_Click(object sender, EventArgs e)
            {
                label3.Text = Cursor.Position.X.ToString();
                label4.Text = Cursor.Position.Y.ToString();
            }

        }

Upvotes: 1

Views: 4172

Answers (2)

Vadim Nuniyants
Vadim Nuniyants

Reputation: 1

You don't even need to add the POINT struct. You can just use the .NET Point class:

static extern bool GetCursorPos(out Point lpPoint);

Upvotes: 0

Jack J Jun- MSFT
Jack J Jun- MSFT

Reputation: 5986

Based on your description, you want to detect mouse clicks outside the form in c#.

First, you can install the nuget package MouseKeyHookto detect global mouseclick event.

Second, you can use windows API to get the position of cursor out of the form.

The following code is a code example and you can have a look.

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

        }

        [StructLayout(LayoutKind.Sequential)]
        public struct POINT
        {
            public int X;
            public int Y;

            public POINT(int x, int y)
            {
                this.X = x;
                this.Y = y;
            }

            public static implicit operator System.Drawing.Point(POINT p)
            {
                return new System.Drawing.Point(p.X, p.Y);
            }

            public static implicit operator POINT(System.Drawing.Point p)
            {
                return new POINT(p.X, p.Y);
            }
        }

        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool GetCursorPos(out POINT lpPoint);
        private void Form1_Load(object sender, EventArgs e)
        {
            Hook.GlobalEvents().MouseClick += MouseClickAll;

        }

        private void MouseClickAll(object sender, MouseEventArgs e)
        {
            POINT p;
            if (GetCursorPos(out p))
            {
                label1.Text = Convert.ToString(p.X) + ";" + Convert.ToString(p.Y);
            }
        }
    }

Tested result:

enter image description here

Upvotes: 5

Related Questions