c# - 将鼠标点击发送到另一个应用程序的 X Y 坐标

标签 c# click window location mouse

我正在尝试将模拟的鼠标点击发送到另一个应用程序。我了解如何实际发送按键点击,这不是问题所在。我需要将鼠标点击发送到另一个应用程序的中心。我可以简单地测试一次并找出坐标并将点击发送到那个 XY 位置,但是有一个问题......当我移动窗口或调整此窗口大小时,XY 坐标显然会不一样。

所以我需要找出如何获取窗口的大小及其位置,然后从中找到中心点。有人知道怎么做吗?非常感谢您的任何回复!

这是我发送鼠标点击的代码

public void SendLeftClick(int x, int y)
{
    int old_x, old_y;
    old_x = Cursor.Position.X;
    old_y = Cursor.Position.Y;

    SetCursorPos(x, y);
    mouse_event(MouseEventFlag.LeftDown, x, y, 0, UIntPtr.Zero);
    mouse_event(MouseEventFlag.LeftUp, x, y, 0, UIntPtr.Zero);
    SetCursorPos(old_x, old_y);
}

最佳答案

您可以使用 GetWindowInfo API:

    [return: MarshalAs(UnmanagedType.Bool)]
    [DllImport("user32.dll", SetLastError = true)]
    private static extern bool GetWindowInfo(IntPtr hwnd, ref WINDOWINFO pwi);

    [StructLayout(LayoutKind.Sequential)]
    struct WINDOWINFO
    {
        public uint cbSize;
        public RECT rcWindow;
        public RECT rcClient;
        public uint dwStyle;
        public uint dwExStyle;
        public uint dwWindowStatus;
        public uint cxWindowBorders;
        public uint cyWindowBorders;
        public ushort atomWindowType;
        public ushort wCreatorVersion;

        public WINDOWINFO(Boolean? filler)
            : this()   // Allows automatic initialization of "cbSize" with "new WINDOWINFO(null/true/false)".
        {
            cbSize = (UInt32)(Marshal.SizeOf(typeof(WINDOWINFO)));
        }

    }
    [StructLayout(LayoutKind.Sequential)]
    struct RECT
    {
        public int left, top, right, bottom;
    }


    private void button1_Click_1(object sender, EventArgs e)
    {
        var p = System.Diagnostics.Process.GetProcessesByName("mspaint");

        if (p.Length == 0) return;

        WINDOWINFO wi = new WINDOWINFO(false);
        GetWindowInfo(p[0].MainWindowHandle, ref wi);

        SendLeftClick((wi.rcWindow.left + wi.rcWindow.right) / 2, (wi.rcWindow.top + wi.rcWindow.bottom) / 2);
    }

关于c# - 将鼠标点击发送到另一个应用程序的 X Y 坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10747004/

相关文章:

c# - 如何实现 StringBuilder 和/或调用 String.FastAllocateString?

c# - 验证方法未按预期工作

javascript - 如何通过 ng-click 将其传递给 Angular 函数?

android - 模拟用户输入

HTML/CSS - 奇怪的调整大小?

c# - BAL在3层架构中的使用?如何从DAL调用方法到BAL

c# - 使用服务器端 webapi 和列表导出到 Excel

javascript - 具有动态 jQuery 选择器的循环事件处理程序

c# - 如何在 Linux 上创建没有控制台的 C# .Net Core 应用程序?

javascript - 尝试关闭弹出窗口并重新加载其父页面