簡體   English   中英

檢測表格外的鼠標點擊 C#

[英]Detect mouse clicks outside the form C#

我是 c# 的新手。 我想跟蹤表單外的鼠標點擊。 試過mousekeyhook,但真的不知道哪個代碼片段將 go 放在哪里。 提前致謝。

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

        }

根據您的描述,您希望在 c# 中檢測表單外的鼠標點擊。

首先,您可以安裝 nuget package MouseKeyHook來檢測全局鼠標點擊事件。

其次,您可以使用 windows API 得到 position 的 Z1791A97A8403739EE0760489A 的形式。

下面的代碼是一個代碼示例,你可以看看。

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

測試結果:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM