C# 在屏幕上获取鼠标坐标



我找到了一个视频和一个我正在处理的源代码;通过单击表单外部来获取坐标。我试图将其与事件联系起来:通过单击(右/左(或按"F11"键;但它不能正常工作。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace iMouse
{
public partial class Events : Form
{
public bool TrackerSt;
public FormMouseCR()
{
InitializeComponent();
}

public void ButtonGetCoord_Click(object sender, EventArgs e)
{
Visible = false;
TrackerSt = true;
int x = Cursor.Position.X;
int y = Cursor.Position.Y;
int size = 10; // Arbitrary size
System.Drawing.Graphics graphics = CreateGraphics();
System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(x - (size / 2), y - (size / 2), size, size);
graphics.DrawRectangle(System.Drawing.Pens.Red, rectangle);
}
private void FormMouseCR_MouseClick(object sender, MouseEventArgs e)
{
if(TrackerSt){
label1.Text = "X = " + e.X + " ; Y = " + e.Y;
TrackerSt = false;
}
}
private void FormMouseCR_MouseMove(object sender, MouseEventArgs e)
{
if(TrackerSt){
label1.Text = "X = " + e.X + " ; Y = " + e.Y;
}
}
}
}

我还考虑将默认光标图标更改为目标图标,并且它是居中的,类似于直线射击瞄准具,但我没有找到类似的东西,只有我在代码中发现的。

但这不能正常工作。 我不知道我失踪了?

我已经用这个更新代码解决了它: 我已经更改了一些执行的顺序并更改了带有威胁的任务。

using System;
using System.Threading;
using System.Windows.Forms;
namespace iMouse
{
public partial class Events : Form
{
public Thread TrackerThread;
public Mutex Checking = new Mutex(false);
public AutoResetEvent Are = new AutoResetEvent(false);
public Events()
{
InitializeComponent();
}
private void Events_Load(object sender, EventArgs e)
{
CheckForIllegalCrossThreadCalls = false;
}
public void Button3_Click(object sender, EventArgs e)
{
Visible = false;
MouseTracker();
}
private void MouseTracker()
{
if (Checking.WaitOne(10))
{
var ctx = new SynchronizationContext();
Are.Reset();
TrackerThread = new Thread(() =>{
while (true)
{
if (Are.WaitOne(1))
{
break;
}
if (MouseButtons == MouseButtons.Left)
{
ctx.Send(CLickFromOutside, null);
break;
}
}
}
);
TrackerThread.Start();
Checking.ReleaseMutex();
}
}
private void CLickFromOutside(object state)
{
Are.Set();
int X = MousePosition.X;
int Y = MousePosition.Y;
TextBox2.Text = X.ToString();
TextBox3.Text = Y.ToString();
Visible = true;
}
}
}

最新更新