将鼠标单击发送到另一个应用程序的X Y坐标

时间:2012-05-25 00:21:07

标签: 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);
}

2 个答案:

答案 0 :(得分:1)

您可以使用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);
    }

答案 1 :(得分:0)

设置光标位置并在mouse_event例程中将0,0设置为X和Y:

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

现在为我工作正常。