Visual Studio 检测窗体外的鼠标单击C#

chhqkbe1  于 2023-03-13  发布在  C#
关注(0)|答案(1)|浏览(298)

我是一个c#新手。我想跟踪窗体外的鼠标点击。尝试了鼠标键钩,但不知道哪段代码会去哪里。提前感谢。

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

        }
kwvwclae

kwvwclae1#

根据您的描述,您希望在C#中检测窗体外的鼠标单击。
首先,您可以安装nuget包MouseKeyHook来检测全局鼠标点击事件。
第二,您可以使用windows API从窗体中获取光标的位置。
下面的代码是一个代码示例,您可以查看一下。

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

检测结果:

相关问题