我是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();
}
}
发布于 2020-05-18 10:27:52
根据您的描述,您希望在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);
}
}
}
测试结果:
https://stackoverflow.com/questions/61817755
复制相似问题