Get Screen Pixel Color - CSharp System.Drawing

CSharp examples for System.Drawing:Color

Description

Get Screen Pixel Color

Demo Code


using System.Windows.Media.Color;
using System.Drawing.Color;
using System.Text.RegularExpressions;
using System.Text;
using System.Runtime.InteropServices;
using System.Linq;
using System.Drawing;
using System.Collections.Generic;
using System;//from  w  w  w.j  ava2 s  .c o  m

public class Main{
        public static Color GetScreenPixelColor(Point location)
        {
            Graphics gfxDisplay = null;
            Bitmap bmp = null;
            Graphics gfxBmp = null;
            try
            {
                IntPtr hdlDisplay = CreateDC("DISPLAY", null, null, IntPtr.Zero);
                gfxDisplay = Graphics.FromHdc(hdlDisplay);
                bmp = new Bitmap(1, 1, gfxDisplay);
                gfxBmp = Graphics.FromImage(bmp);
                IntPtr hdlScreen = gfxDisplay.GetHdc();
                IntPtr hdlBmp = gfxBmp.GetHdc();
                BitBlt(hdlBmp, 0, 0, 1, 1, hdlScreen, location.X, location.Y, 13369376);
                gfxDisplay.ReleaseHdc(hdlScreen);
                gfxBmp.ReleaseHdc(hdlBmp);
                return bmp.GetPixel(0, 0);
            }
            finally
            {
                gfxBmp.Dispose();
                bmp.Dispose();
                gfxDisplay.Dispose();
            }
        }
        [DllImport("gdi32.dll")]
        static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos);
}

Related Tutorials