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

Do I need to introduce delays when simulating a mouse click with SendInput API?

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

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;
}

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

SendInput 的文档包含以下内容:

The SendInput function inserts the events in the INPUT structures serially into the keyboard or mouse input stream. These events are not interspersed with other keyboard or mouse input events inserted either by the user (with the keyboard or mouse) or by calls to keybd_event, mouse_event, or other calls to SendInput.

这就是引入 SendInput 的原因。在 SendInput 的各个调用之间人为延迟完全违背了它的目的。

简短的回答是:不,您不需要在合成输入之间引入延迟。您也不需要调用 SetCursorPos; INPUT 结构已经包含鼠标输入的位置。

当然,如果您选择 UI Automation,您就不必处理这些问题。 UI 自动化的设计目标是 "to manipulate the UI by means other than standard input. UI Automation also allows automated test scripts to interact with the UI."