简体   繁体   English

检测表格外的鼠标点击 C#

[英]Detect mouse clicks outside the form C#

i'm a newbie in c#.我是 c# 的新手。 I want to track mouse clicks outside the form.我想跟踪表单外的鼠标点击。 Tried mousekeyhook, but don't really know which snippet of code will go where.试过mousekeyhook,但真的不知道哪个代码片段将 go 放在哪里。 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#.根据您的描述,您希望在 c# 中检测表单外的鼠标点击。

First, you can install the nuget package MouseKeyHook to detect global mouseclick event.首先,您可以安装 nuget package MouseKeyHook来检测全局鼠标点击事件。

Second, you can use windows API to get the position of cursor out of the form.其次,您可以使用 windows API 得到 position 的 Z1791A97A8403739EE0760489A 的形式。

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:测试结果:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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