In the previous article, C # _ dynamically obtained the mouse coordinates, and it was easy to get the dynamic coordinates when the mouse was moved. Then, how can we get the coordinates and the color value like the screen color Acquisition Tool? Here we still use the original ecological API method.
API declaration:
/// <Summary> /// obtain the device scenario of the specified window // </summary> /// <param name = "hwnd"> obtain the window of the device scenario. If the value is 0, you need to obtain the device scenario handle of the entire screen DC </param> /// <returns> specified window, error: 0 </returns> [DllImport ("user32.dll")] public static extern IntPtr GetDC (IntPtr hwnd ); /// <summary> /// release the specified device scenario obtained by calling the GetDC function /// </summary> /// <param name = "hwnd"> to release the device scenario-related window handle </param> /// <param name = "hdc"> the device scenario handle to be released </param> /// <returns> is successfully executed 1, otherwise 0 </returns> [DllImport ("user32.dll")] public static extern Int32 ReleaseDC (IntPtr hwnd, IntPtr hdc ); /// <summary> /// obtain the RGB value of a pixel in the specified device scenario /// </summary> /// <param name = "hdc"> handle of the device scenario </param> /// <param name = "nXPos"> abscissa to be checked in logical coordinates </param> /// <param name = "nYPos"> The ordinate to be checked in logical coordinates </param> // <returns> the color of the specified vertex </returns> [DllImport ("gdi32.dll")] public static extern uint GetPixel (IntPtr hdc, int nXPos, int nYPos );
Usage:
public Color GetColor(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;}
Here, the x and y parameters are the mouse coordinates we have obtained. Portal: C # _ dynamically obtains mouse coordinates.