DEV Community

Juan Diego Mejía Maestre
Juan Diego Mejía Maestre

Posted on • Updated on

Cómo obtener el color que esta debajo del cursor del mouse en C#

Para obtener el color de bajo del cursor del mouse solo agregamos este código al formulario

[DllImport("user32.dll")]
private static extern bool GetCursorPos(ref Point lpPoint);


[DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
public static extern int BitBlt(IntPtr hDC, int x, int y, int nWidth, int nHeight, IntPtr hSrcDC, int xSrc, int ySrc, int dwRop);

Enter fullscreen mode Exit fullscreen mode

Importamos todas las librerías necesaria.

Primero obtenemos la pantalla

Bitmap screenPixel = new Bitmap(1, 1, PixelFormat.Format32bppArgb);
Enter fullscreen mode Exit fullscreen mode

Y creamos este método para obtener el color


public Color GetColor(Point location)
        {
            using (Graphics gdest = Graphics.FromImage(screenPixel))
            {
                using (Graphics gsrc = Graphics.FromHwnd(IntPtr.Zero))
                {
                    IntPtr hSrcDC = gsrc.GetHdc();
                    IntPtr hDC = gdest.GetHdc();
                    int retval = BitBlt(hDC, 0, 0, 1, 1, hSrcDC, location.X, location.Y, (int)CopyPixelOperation.SourceCopy);
                    gdest.ReleaseHdc();
                    gsrc.ReleaseHdc();
                }
            }

            return screenPixel.GetPixel(0, 0);
        }

Enter fullscreen mode Exit fullscreen mode

Top comments (0)