简体   繁体   中英

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

        }

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

First, you can install the nuget package MouseKeyHook to 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:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM