How i can simulate a double mouse click on window ( i khow handle) on x, y coordinate, using SendInput?

点点圈 提交于 2019-11-28 06:05:01
void DoubleClick(int x, int y)
{
    const double XSCALEFACTOR = 65535 / (GetSystemMetrics(SM_CXSCREEN) - 1);
    const double YSCALEFACTOR = 65535 / (GetSystemMetrics(SM_CYSCREEN) - 1);

    POINT cursorPos;
    GetCursorPos(&cursorPos);

    double cx = cursorPos.x * XSCALEFACTOR;
    double cy = cursorPos.y * YSCALEFACTOR;

    double nx = x * XSCALEFACTOR;
    double ny = y * YSCALEFACTOR;

    INPUT Input={0};
    Input.type = INPUT_MOUSE;

    Input.mi.dx = (LONG)nx;
    Input.mi.dy = (LONG)ny;

    Input.mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP;

    SendInput(1,&Input,sizeof(INPUT));
    SendInput(1,&Input,sizeof(INPUT));

    Input.mi.dx = (LONG)cx;
    Input.mi.dy = (LONG)cy;

    Input.mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE;

    SendInput(1,&Input,sizeof(INPUT));
}

You can use GetWindowRect() to get the window position from its handle and pass relative x and y to DoubleClick function:

RECT rect;
GetWindowRect(hwnd, &rect);

HWND phwnd = GetForegroundWindow();

SetForegroundWindow(hwnd);

DoubleClick(rect.left + x, rect.top + y);

SetForegroundWindow(phwnd); // To activate previous window

This will simulate a double click at certain coordinates

  SetCursorPos(X,Y);
  mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP,0,0,0,0);
  mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP,0,0,0,0);

You can specify your goal (best) or the method, but if you try to specify both, more often than not the answer is going to be "that doesn't work like that".

SendInput doesn't work like that, it simulates mouse activity on the screen, which will be delivered to whatever window is visible at that location (or has mouse capture), not the window of your choice.

To deliver a double-click to a specific window, try PostMessage(hwnd, WM_LBUTTONDBLCLK, 0, MAKEDWORD(x, y)).

There's a piece of code in this website. Try using the function LeftClick() twice in succession. That does the trick according to this guy.

Since my 'reputation' is not high enough (yet), I'd like to comment on #fardjad's solution: it works great, but one might add following to the "main" routine:

SetForegroundWindow(hwnd);
SetCursorPos(rect.left + x, rect.top + y);
// which shows your current mouseposition...
// during my testing, I used a _getch() so that I actually could verify it
Sleep(nWinSleep);
// delay the mouseclick, as window might not get to foreground quick enough;
   took me awhile to figure this one out...
DoubleClick(rect.left + x, rect.top + y);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!