winapimouseleftbuttondown

Issue with generating left click in win32 api?



Below is my code to generate left click using win32 api. The problem is that it gets stuck and does not return to main. When i press Ctrl+c, then it returns to main. BUT when I call it twice, to simulate double click then it is fine. Is there anything wrong with this code? Thank you.

void LeftClick(void)
{  
  INPUT    Input={0};

  // left down 
  Input.type      = INPUT_MOUSE; /*The event is a mouse event. Use the mi structure of the union.*/
  Input.mi.dwFlags  = MOUSEEVENTF_LEFTDOWN;
  SendInput(1,&Input,sizeof(INPUT));

  // left up
  ZeroMemory(&Input,sizeof(INPUT));
  Input.type      = INPUT_MOUSE;
  Input.mi.dwFlags  = MOUSEEVENTF_LEFTUP;
  SendInput(1,&Input,sizeof(INPUT));
}

Solution

  • If you're not committed to using SendInput, I've had success in the past using SendMessage on the desired hWnd with WM_LBUTTONDOWN then again with WM_LBUTTONUP.

    Most buttons also simulate a click with keyboard entry. You can use SendMessage to your desired hWnd with WM_KEYDOWN and wParam VK_SPACE, then WM_KEYUP with VK_SPACE to complete the space bar keypress simulation.