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

时间:2015-03-16 00:08:21

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

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

1 个答案:

答案 0 :(得分:5)

SendInput的文档包含以下内容:

  

SendInput 函数将INPUT结构中的事件串行插入键盘或鼠标输入流。这些事件没有穿插用户(使用键盘或鼠标)或通过调用keybd_eventmouse_event或其他对 SendInput的调用插入的其他键盘或鼠标输入事件。强>

这就是为什么引入SendInput的原因。在SendInput的单个调用之间设置人为延迟完全违背了其目的。

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

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