繁体   English   中英

c#鼠标单击模拟以隐藏在x / y位置

[英]c# Mouse click simulation to hwnd at x/y position

在过去的3天里,我发现了很多用于模拟鼠标单击其他窗口的代码。 但他们都没有成功。 我有窗口句柄hwnd和必须单击的X / Y位置(像素)。 X / Y位置是窗口内部的位置。

我发现的最好的代码是:

public void click(IntPtr hWnd, int x, int y)
{        
    RECT rec = new RECT();
    GetWindowRect(hWnd, ref rec);
    int newx = x - rec.Left;
    int newy = y - rec.Top;

    SendMessage(hWnd, WM_LBUTTONDOWN, 1, ((newy << 0x10) | newx));
    SendMessage(hWnd, WM_LBUTTONUP, 0, ((newy << 0x10) | newx));
}

[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
    public int Left;
    public int Top;
    public int Right;
    public int Bottom;
}

[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int SendMessage(IntPtr A_0, int A_1, int A_2, int A_3);


[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);

但是它不能100%正确地工作。 它在正确的窗口上模拟鼠标单击,但是在我的真实光标所在的位置。 单击此按钮后,我的鼠标跳到屏幕上的随机位置。 我希望有人能编写一个有效的代码,并简要说明其工作方式。

谢谢

使用此代码模拟鼠标左键在某个位置的点击

//This is a replacement for Cursor.Position in WinForms
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern bool SetCursorPos(int x, int y);

[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);

public const int MOUSEEVENTF_LEFTDOWN = 0x02;
public const int MOUSEEVENTF_LEFTUP = 0x04;

//This simulates a left mouse click
public static void LeftMouseClick(int xpos, int ypos)
{
    SetCursorPos(xpos, ypos);
    mouse_event(MOUSEEVENTF_LEFTDOWN, xpos, ypos, 0, 0);
    mouse_event(MOUSEEVENTF_LEFTUP, xpos, ypos, 0, 0);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM