blez's : blog

code / design / music and more

Get the color under cursor in hex

Leave a comment

The following code gets the pixel color at position. HexConvert converts the color to web hex format.

        // use with GetColorAt(System.Windows.Forms.Cursor.Position) to get the color under the cursor
        [DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
        private static extern int BitBlt(IntPtr hDC, int x, int y, int nWidth, int nHeight, IntPtr hSrcDC, int xSrc, int ySrc, int dwRop);

        private static Color GetColorAt(Point location)
            var screenPixel = new Bitmap(1, 1, PixelFormat.Format32bppArgb);

            using (var gdest = Graphics.FromImage(screenPixel))
                using (var gsrc = Graphics.FromHwnd(IntPtr.Zero))
                    var hSrcDC = gsrc.GetHdc();
                    var hDC = gdest.GetHdc();

                    BitBlt(hDC, 0, 0, 1, 1, hSrcDC, location.X, location.Y, (int) CopyPixelOperation.SourceCopy);

            return screenPixel.GetPixel(0, 0);

        private static string HexConvert(Color color) {
            return "#" + color.R.ToString("X2") + color.G.ToString("X2") + color.B.ToString("X2");

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s