Simulate mouse click

1

I need to simulate the mouse click, but I can not use PostMessage nor mouse_event . Is there any other way to send the click?

    
asked by anonymous 03.05.2015 / 06:29

1 answer

1

You can use the SendInput API.

  

Synthesize keystrokes, mouse movements, and button clicks.

     

Obs : This role is subject to UIPI . Applications shall be   injecting the input only in applications that are at a level of   integrity equal or less.

Assuming you first want to move the cursor to a specific point, you must use absolute coordinates in the interval between 0 and 65535 , so to correctly compute the coordinates of the screen, use the following function:

function ObterCoordenada(const Indice, Posicao: Integer): Integer;
begin
  Result := (65535 div (GetSystemMetrics (Indice) -1)) * Posicao;
end;

Now the function responsible for moving the cursor and simulating the left click with the function SendInput :

procedure SimularClick(const X, Y: Integer);
var
Entrada: array [0..1] of TInput;
begin
  ZeroMemory(@Entrada, SizeOf(Entrada));
  // Primeiramente move o cursor do mouse a uma coordenada especifica, em Pixels!
  Entrada[0].Itype := INPUT_MOUSE;
  Entrada[0].mi.dwFlags := MOUSEEVENTF_MOVE or MOUSEEVENTF_ABSOLUTE;
  Entrada[0].mi.dx := ObterCoordenada(SM_CXSCREEN, X);
  Entrada[0].mi.dy := ObterCoordenada(SM_CYSCREEN, Y);
  SendInput(1, Entrada[0], sizeof(TInput)); // Envia o pedido

  // Realiza o click com o botão esquerdo do mouse
  Entrada[1].Itype := INPUT_MOUSE;
  Entrada[1].mi.dwFlags := MOUSEEVENTF_LEFTDOWN or MOUSEEVENTF_LEFTUP;

  SendInput(1, Entrada[1], sizeof(TInput));   // Envia o pedido
end;

Example usage:

procedure TForm1.Button1Click(Sender: TObject);
begin
  SimularClick(625, 486); // Onde "625" é X e "486", Y
end; 
    
03.05.2015 / 16:27