Jump to content
Tom F

What color did a user click on in an Image

Recommended Posts

 

When a user clicks on the TImage below, I want to know which arrow, if any, they've clicked on.  The image is loaded in Image1.Picture from a bmp that is loaded at runtime.

The code below works on my desktop machine, but not on a laptop,  where it most often returns 'You did not click on an arrow.' 

Perhaps this is due to dependencies on screen size, resolution, color depth, or ??? I'm not really familiar with how HDC, GetCursorPos, and GetPixel work let alone in different environments.
Any suggestions for a way to reliably detect which arrow is clicked. 32-bit VCL app.


Procedure TForm1.Image1Click(Sender: TObject);
const
  COLOR_VIOLET = 4002090;  // Determined empirically by examining at result of GetPixel call below
  COLOR_PURPLE = 8334696;
  COLOR_BLUE   = 11757312;
  COLOR_GREEN  = 7186176;
  COLOR_RED    = 255;
var
  P: TPoint;
  dc: HDC;
  ClickedColor: TColor;
begin
  GetCursorPos(P);
  dc := GetDC(0);
  ClickedColor := GetPixel(dc, P.X, P.Y);
  if (ClickedColor = COLOR_VIOLET) then
    ShowMessage('Violet')
  else if (ClickedColor = COLOR_PURPLE) then
    ShowMessage('Purple')
  else if (ClickedColor = COLOR_BLUE) then
    ShowMessage('Blue')
  else if (ClickedColor = COLOR_GREEN) then
    ShowMessage('Green')
  else if (ClickedColor = COLOR_RED) then
    ShowMessage('Red')
  else
    ShowMessage('You did not click on an arrow.')
end;

 

Arrows.png.10a7bb0cdd49ccbb055d73cb65cae98d.png

Share this post


Link to post

The problem is probably that the mouse coordinates do not match the pixel coordinates. If you click on the upper left corner, are you getting x=0 and y=0? If not, try ScreenToClient. Once you get that position right, try the lower right corner. Do you get x=Bitmap.With and y=Bitmap.Height? If not try to multiply with Image.Width/Bitmap.Width and Image.Height/Bitmap.Height. And then you might have to consider that y coordinates of bitmaps can be upside down.

  • Like 1

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×