[C#] Get Pixel Color At X,Y

Hello,

a simple trick for you to get pixel color on a particular position of your screen with Windows GDI32.dll API libs.

First of all, you need to import Win32 API:

[code lang=”csharp” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”][DllImport( "user32.dll" )]
static extern IntPtr GetDC( IntPtr hwnd );

[DllImport( "user32.dll" )]
static extern Int32 ReleaseDC( IntPtr hwnd, IntPtr hdc );

[DllImport( "gdi32.dll" )]
static extern uint GetPixel( IntPtr hdc, int nXPos, int nYPos );[/code]

after that, create a function like this that return color in ARGB:

[code lang=”csharp” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]static public System.Drawing.Color GetPixelColor( int x, int y )
{
IntPtr hdc = GetDC( IntPtr.Zero );
uint pixel = GetPixel( hdc, x, y );
ReleaseDC( IntPtr.Zero, hdc );
Color color = Color.FromArgb( ( int )( pixel & 0x000000FF ),
( int )( pixel & 0x0000FF00 ) >> 8,
( int )( pixel & 0x00FF0000 ) >> 16 );
return color;
}[/code]

you can call it simply GetPixelColor( 0, 100 );

That’s all.

Rif: albertopasca.it

Alberto Pasca
Latest posts by Alberto Pasca (see all)