Sep 14, 2009

Color under Cursor in C#

To easily “steal” some styles and colors from a given web app, I wrote the following little application to find out the color under the mouse pointer.


And here’s the code for the major parts:

using System;
using System.Drawing;
using System.Runtime.InteropServices;

namespace ColorUnderPixel
    public class ColorUnderCursor
        public static extern uint GetPixel(IntPtr hDC, int XPos, int YPos);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern bool GetCursorPos(out POINT pt);

        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern IntPtr GetWindowDC(IntPtr hWnd);

        /// <summary>
        /// Gets the System.Drawing.Color from under the mouse cursor.
        /// </summary>
        /// <returns>The color value.</returns>
        public static Color Get()
            IntPtr dc = GetWindowDC(IntPtr.Zero);

            POINT p;
            GetCursorPos(out p);

            long color = GetPixel(dc, p.X, p.Y);
            return Color.FromArgb((int)color);

    public struct POINT
        public int X;
        public int Y;
        public POINT(int x, int y)
            X = x;
            Y = y;

[Update] Please note that the hex values must be reversed to represent a RGB value like in a CSS

background-color: #3b5998;

1 comment: