虚拟鼠标单击非活动进程的位置?

时间:2019-11-30 05:33:52

标签: c#

我正在使用MEmu(这是一个Android模拟器)来研究android应用的自动化程度。

基本上,我想在仿真器中搜索图像,并在其上进行“虚拟点击”(无需移动鼠标),即使仿真器已最小化也是如此。

我进行了很多搜索,但没有找到可行的解决方案。

我可以做的是“单击”,但是过程窗口必须处于活动状态(并处于聚焦状态)并且鼠标移动。

public class ClickOnPointTool
{

    [DllImport("user32.dll")]
    static extern bool ClientToScreen(IntPtr hWnd, ref Point lpPoint);

    [DllImport("user32.dll")]
    internal static extern uint SendInput(uint nInputs, [MarshalAs(UnmanagedType.LPArray), In] INPUT[] pInputs, int cbSize);

    #pragma warning disable 649
    internal struct INPUT
    {
        public UInt32 Type;
        public MOUSEKEYBDHARDWAREINPUT Data;
    }

    [StructLayout(LayoutKind.Explicit)]
    internal struct MOUSEKEYBDHARDWAREINPUT
    {
        [FieldOffset(0)]
        public MOUSEINPUT Mouse;
    }

    internal struct MOUSEINPUT
    {
        public Int32 X;
        public Int32 Y;
        public UInt32 MouseData;
        public UInt32 Flags;
        public UInt32 Time;
        public IntPtr ExtraInfo;
    }

    #pragma warning restore 649

    public static void ClickOnPoint(IntPtr wndHandle, Point clientPoint)
    {
        var oldPos = Cursor.Position;

        /// get screen coordinates
        ClientToScreen(wndHandle, ref clientPoint);

        /// set cursor on coords, and press mouse
        Cursor.Position = new Point(clientPoint.X, clientPoint.Y);

        var inputMouseDown = new INPUT();
        inputMouseDown.Type = 0; /// input type mouse
        inputMouseDown.Data.Mouse.Flags = 0x0002; /// left button down

        var inputMouseUp = new INPUT();
        inputMouseUp.Type = 0; /// input type mouse
        inputMouseUp.Data.Mouse.Flags = 0x0004; /// left button up

        var inputs = new INPUT[] { inputMouseDown, inputMouseUp };
        SendInput((uint)inputs.Length, inputs, Marshal.SizeOf(typeof(INPUT)));

        /// return mouse 
        Cursor.Position = oldPos;
    }

 }

0 个答案:

没有答案