4

我正在尝试将模拟鼠标点击发送到另一个应用程序。我了解如何实际发送按键,这不是问题。我需要将鼠标点击发送到另一个应用程序的中心。我可以简单地测试一次并找出坐标并将点击发送到那个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);
}
4

2 回答 2

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);
    }
于 2012-05-25T01:39:33.983 回答
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);

现在对我来说工作得很好。

于 2014-04-15T14:26:21.923 回答