How to click on image using powershell?

by dalton_moen , in category: Third Party Scripts , 2 months ago

How to click on image using powershell?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raphael_tillman , 2 months ago

@dalton_moen 

To click on an image using PowerShell, you can use the SendInput method in combination with the GetCursorPos method.


Here is an example script that demonstrates how to click on an image using PowerShell:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
Add-Type @"
  using System;
  using System.Runtime.InteropServices;

  public class UserInput {
    [DllImport("user32.dll", SetLastError=true)]
    public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);

    [DllImport("user32.dll")]
    public static extern bool SetCursorPos(int X, int Y);

    [DllImport("user32.dll")]
    public static extern bool GetCursorPos(out POINT lpPoint);

    [StructLayout(LayoutKind.Sequential)]
    public struct POINT {
      public int X;
      public int Y;
    }

    public const int MOUSEEVENTF_LEFTDOWN = 0x02;
    public const int MOUSEEVENTF_LEFTUP = 0x04;
  }
"@

function ClickOnImage {
  param(
    [int]$x,
    [int]$y
  )

  $point = New-Object UserInput+POINT
  [void][UserInput]::GetCursorPos([ref]$point)
  $currentX = $point.X
  $currentY = $point.Y

  [void][UserInput]::SetCursorPos($x, $y)
  [void][UserInput]::mouse_event([UserInput]::MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
  [void][UserInput]::mouse_event([UserInput]::MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
  [void][UserInput]::SetCursorPos($currentX, $currentY)
}

# Replace the coordinates with the coordinates of the image you want to click on
$x = 100
$y = 100

ClickOnImage $x $y


In this script:

  1. We define a UserInput class with the necessary methods and constants for mouse input.
  2. We create a function ClickOnImage that takes the X and Y coordinates of the image as parameters and simulates a mouse click at that position.
  3. We retrieve the current cursor position, move the cursor to the specified X and Y coordinates, perform a left mouse button down event, then perform a left mouse button up event, and finally move the cursor back to its original position.
  4. Finally, we call the ClickOnImage function with the X and Y coordinates of the image you want to click on.


Remember to replace the coordinates in the script with the actual coordinates of the image you want to click on.