我是C#的新手。我想跟踪表单外的鼠标单击。尝试使用mousekeyhook,但实际上并不知道哪个代码段会去哪里。预先感谢。
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软件包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);
}
}
}
测试结果: