Home > Software engineering >  How to click on specific pixel of screenshot in C#
How to click on specific pixel of screenshot in C#

Time:12-03

I am trying to make a bot for a game by taking screenshot of it non-stop and scanning the screenshot and trying to find a specific pixel by checking the RGB color of it and simulate a click.

how can I simulate a click on specific pixel?

Thank you

I already have the screenshot part done

CodePudding user response:

// Take the screenshot
Bitmap screenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics graphics = Graphics.FromImage(screenshot);
graphics.CopyFromScreen(0, 0, 0, 0, screenshot.Size);

// Scan the screenshot to find the desired pixel
Color pixelColor = screenshot.GetPixel(x, y);

// Check if the pixel has the desired color
if (pixelColor.R == r && pixelColor.G == g && pixelColor.B == b)
{
    // Set the cursor's position to the desired pixel
    System.Drawing.Point cursorPos = new System.Drawing.Point(x, y);
    Cursor.Position = cursorPos;

    // Simulate a mouse click
    mouse_event(MOUSEEVENTF_LEFTDOWN, x, y, 0, 0);
    mouse_event(MOUSEEVENTF_LEFTUP, x, y, 0, 0);
}

In this example, x and y are the coordinates of the pixel on the screenshot that you want to click on, and r, g, and b are the desired red, green, and blue values of the pixel, respectively. You can adjust these values to set the cursor's position to the desired pixel and check for the desired color.

Note: This example uses the GetPixel and mouse_event methods from the System.Drawing and user32.dll libraries, respectively, to simulate a mouse click. These methods are not part of the C# language, so you will need to add references to the System.Drawing and user32.dll libraries and include the System.Drawing and System.Runtime.InteropServices namespaces in your code in order to use them. You can find more information on how to do this in the Microsoft documentation.

  • Related