使用SendInput API模拟鼠标单击时是否需要引入延迟?

c00*_*0fd -1 c++ windows winapi sendinput

我需要能够在另一个进程中模拟鼠标单击控件.我想出了以下方法:

BOOL SimulateMouseClick(POINT* pPntAt)
{
    //Simulate mouse left-click
    //'pPntAt' = mouse coordinate on the screen
    //RETURN:
    //      = TRUE if success
    BOOL bRes = FALSE;

    if(pPntAt)
    {
        //Get current mouse position
        POINT pntMouse = {0};
        BOOL bGotPntMouse = ::GetCursorPos(&pntMouse);

        //Move mouse to a new position
        ::SetCursorPos(pPntAt->x, pPntAt->y);

        //Send mouse click simulation
        INPUT inp = {0};
        inp.type = INPUT_MOUSE;
        inp.mi.dx = pPntAt->x;
        inp.mi.dy = pPntAt->y;
        inp.mi.dwFlags = MOUSEEVENTF_LEFTDOWN;
        if(SendInput(1, &inp, sizeof(inp)) == 1)
        {
            //Do I need to wait here?
            Sleep(100);

            inp.mi.dwFlags = MOUSEEVENTF_LEFTUP;
            if(SendInput(1, &inp, sizeof(inp)) == 1)
            {
                //Do I need to wait here before restoring mouse pos?
                Sleep(500);

                //Done
                bRes = TRUE;
            }
        }

        //Restore mouse
        if(bGotPntMouse)
        {
            ::SetCursorPos(pntMouse.x, pntMouse.y);
        }
    }

    return bRes;
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,我是否需要引入像人类鼠标点击那样的人工延迟?

IIn*_*ble 5

SendInput的文档包含以下内容:

SendInput函数插入在事件INPUT结构串联到键盘或鼠标输入流.这些事件不会插入用户(使用键盘或鼠标)插入的其他键盘或鼠标输入事件,也不会调用keybd_event,mouse_event或其他SendInput调用.

这就是为什么SendInput被引入的原因.在个别电话之间设置人为延迟SendInput完全违背其目的.

简短的回答是:不,您不需要在合成输入之间引入延迟.你也不需要打电话SetCursorPos; 该INPUT结构已经包含了鼠标输入的位置.

当然,如果您选择使用UI Automation,则不必处理任何此类问题.UI Automation的设计目标是"通过标准输入以外的方式操作UI.UI Automation还允许自动化测试脚本与UI交互."