3

Ok so I'm trying to get a little more advanced here and one of the things i want to learn how to do is get pixel color or data from a certain position on the screen. I have searched a lot but it seems most people want to do this in c or c++.

Im making a program that scans a location on the screen for a certain color. If that location contains anything with orange then the number in my window turns into a 1 for true or 0 for false. The background of my window is transparent, if that matters at all.

I have only come across Graphics.CopyFromScreen() and bitmap.GetPixel();

Thanks

IzzM
  • 81
  • 1
  • 1
  • 5
  • Does this help:- http://stackoverflow.com/questions/1483928/how-to-read-the-color-of-a-screen-pixel – Rahul Tripathi Apr 07 '14 at 05:16
  • Wow thanks i couldn't find that before. Although i was afraid i would come across the old [DLLImport] user32.dll thing again. i hate messing with those native win32 functions because its far more advanced that i would like to go, but thanks, ill give a try. – IzzM Apr 07 '14 at 05:18

2 Answers2

2

To capture specific rectangle form the screen use the following code

    public Bitmap CaptureFromScreen(Rectangle rect)
    {
        Bitmap bmpScreenCapture = null;

        if (rect == Rectangle.Empty)//capture the whole screen
        {
            rect = Screen.PrimaryScreen.Bounds;
        }

        bmpScreenCapture = new Bitmap(rect.Width,rect.Height);

        Graphics p = Graphics.FromImage(bmpScreenCapture);


            p.CopyFromScreen(rect.X,
                     rect.Y,
                     0, 0,
                     rect.Size,
                     CopyPixelOperation.SourceCopy);


        p.Dispose();

        return bmpScreenCapture;
    }

To Get The color form a specific location use the function

    public Color GetColorFromScreen(Point p)
    {
        Rectangle rect = new Rectangle(p, new Size(2, 2));

        Bitmap map = CaptureFromScreen(rect);

        Color c = map.GetPixel(0, 0);

        map.Dispose();

        return c;
    }
yazan
  • 600
  • 7
  • 12
  • Im still testing things out to see what will work and what won't. Thanks, ill give this a try too. – IzzM Apr 07 '14 at 07:00
  • Why the duplicated code? Just check if the rectangle is empty and if so assign the screens rectangle to it. Then you can just use the 'just the rectangle' sections. – James Coyle Aug 13 '18 at 07:22
  • @JamesCoyle Thanks, I've updated the code. – yazan Aug 13 '18 at 14:58
0

Please see the following reference, I think this is what you need:

http://www.codeproject.com/Articles/24850/Geting-pixel-color-from-screen-shoot-image

Adel
  • 1,468
  • 15
  • 18