检测窗体外的鼠标点击 C#
Detect mouse clicks outside the form C#
我是 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);
}
}
}
测试结果:
我是 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);
}
}
}
测试结果: