Search code examples
delphipositionscreenmousepixel

How do I return color based on X,Y coordinates from the screen?


This is for Delphi (7).

I have been trying to find a pixel searcher for the screen, but without much help. At the most I found something that will take an entire screenshot and store it in a canvas, but I am not sure if that is really necessary, as the only purpose is to check a given coordination.

I basically just need something that would make this works:

procedure TForm1.Button1Click(Sender: TObject);
begin
if(Checkcolor(1222,450) == 000000) then
showmessage('Black color present at coordinates');
end;

Solution

  • Try with this code:

    function ColorPixel(P: TPoint): TColor;
    var
      DC: HDC;
    begin
      DC:= GetDC(0);
      Result:= GetPixel(DC,P.X,P.Y);
      ReleaseDC(0,DC);
    end;
    

    An example program to show hex color:

    var
      P: TPoint;
      R,G,B: integer;
    begin
      GetCursorPos(P);
      Color:= ColorPixel(P);
      R := Color and $ff;
      G := (Color and $ff00) shr 8;
      B := (Color and $ff0000) shr 16;
      ShowMessage(format('(%d,%d,%d)',[R,G,B]));
    end;
    

    If you need the pixel of a specific window, you need to modify the GetDC call using the window handle.

    GetDc https://msdn.microsoft.com/en-us/library/windows/desktop/dd144871(v=vs.85).aspx GetPixel https://msdn.microsoft.com/en-us/library/windows/desktop/dd144909(v=vs.85).aspx

    EDIT: In the example, you can extract RGB components using the functions (Windows unit) GetRValue, GetGValue, GetBValue, instead of bit operations. For example:

    R:= GetRValue(Color);