Search code examples
c#visual-studio-2010mouseeventpixel

mouse position and give the position color


How can I get the color of a pixel at the location of the cursor? I know how to get the mouses position using MousePosition but I can not figure out how to get the pixel color at that location. I write the code put I have no result when run

 private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
    {


                    s= pictureBox1.PointToClient(Cursor.Position);        

                    bitmap.SetPixel(s.X / 40, s.Y / 40, Color.Red);

                    }

Solution

  • It is easier to use the e.Location point in the parameter of the Mouseclick event:

    Color c = ( (Bitmap)pictureBox1.Image).GetPixel(e.X, e.Y);
    

    This assumes that indeed the bitmap is in the PicturBox's Image, not painted on top of the Control..

    Make sure the event is actually hooked up!

    To set a clicked pixel to, say red, you would get the Bitmap from the PB's Image and set the pixels, then move the Bitmap back in::

    Bitmap bmp = (Bitmap)pictureBox1.Image;
    bmp.SetPixel(e.X, e.Y, Color.Red);
    pictureBox1.Image = bmp;
    

    also in the MouseClick event.

    If you want to get a larger mark you should use the Graphics methods, maybe like this:

    using (Graphics G = Graphics.FromImage(pictureBox1.Image))
    {
       G.DrawEllipse(Pens.Red, e.X - 3, e.Y - 3, 6, 6);
    }
    

    Update: To combine getting and setting you could write:

    Bitmap bmp = (Bitmap)pictureBox1.Image;
    Color target = Color.FromArgb(255, 255, 255, 255); 
    Color c == bmp .GetPixel(e.X, e.Y);
    if (c == target ) 
        {
           bmp.SetPixel(e.X, e.Y, Color.Red);
           pictureBox1.Image = bmp;
        }
    else MessageBox.Show("Click only on white spots! You have hit " + c.ToString(),
                         "Wrong spot! ");