[英]Changing mouse position with C#
我正在创建一个程序来对我的首选游戏执行宏,并且我必须为我的鼠标指针设置一个自定义 position。 我正在使用这段代码:
public partial class Form1 : Form
{
[DllImport("user32.dll")]
public static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vlc);
[DllImport("user32.dll")]
public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
[DllImport("user32.dll")]
static extern bool SetCursorPos(int X, int Y);
public static int status = 0;
const int WM_PARENTNOTIFY = 0x210;
const int WM_LBUTTONDOWN = 0x201;
public Form1()
{
InitializeComponent();
Boolean success = Form1.RegisterHotKey(this.Handle, this.GetType().GetHashCode(), 0x0000, 0x23);//Set hotkey as 'END'
}
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x0312)
{
if (status == 0)
{
label3.Text = "Status: ativo";
status = 1;
}
else
{
label3.Text = "Status: inativo";
status = 0;
}
}
if (m.Msg == WM_LBUTTONDOWN || (m.Msg == WM_PARENTNOTIFY && (int)m.WParam == WM_LBUTTONDOWN)) // on left click event
{
if (status == 1)
{
SetCursorPos(100,200);
}
}
base.WndProc(ref m);
}
private void Form1_Load(object sender, EventArgs e)
{
label4.Text = "";
}
private void trackBar1_ValueChanged(object sender, EventArgs e)
{
this.KeyPreview = true;
label4.Text = trackBar1.Value.ToString();
}
}
它仅在形式集中时才有效,在全球范围内无效。
我必须怎么做才能解决这个问题?
谢谢你。
您正在将热键注册到表单 ( this.Handle
)。 您需要注册目标应用程序的句柄。
您可以通过调用 user32 FindWindow 找到窗口的句柄,如下所示
或者您可以使用本机 C#:
IntPtr hwnd = IntPtr.Zero;
foreach (Process process in Process.GetProcesses())
{
if (process.MainWindowTitle == "My Game")
{
hwnd = process.MainWindowHandle;
}
}
RegisterHotKey(hwnd, this.GetType().GetHashCode(), 0x0000, 0x23);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.