C # Color Picker

Source: Internet
Author: User

Idle to have nothing to do, wrote a color picker. The principle is actually very simple, it takes only two steps,

    1. Gets the position of the mouse cursor,
    2. Gets the RGB color value for the position of the current mouse cursor.

Get the position of the mouse cursor:

System.Drawing.Point p = mouseposition;


Gets the RGB color value for the specified coordinates, where we need to use 1 WIN32 API functions:GetPixel.

The role of the GetPixel function is to retrieve the RGB color value of the pixel of the coordinate point, the function prototype is COLORREF GetPixel (hdc hdc, int nxpos, int nypos)

Since this is a system-provided API function, we cannot use it directly in C #, we need to "translate" it to make C # call:

/// <summary>///The function retrieves the RGB color value of the pixel at the specified coordinate point. /// </summary>/// <param name= "HDC" >The device environment handle. </param>/// <param name= "Nxpos" >Specifies the logical x-axis coordinates of the pixel points to check. </param>/// <param name= "Nypos" >Specifies the logical y-axis coordinates of the pixel points to check. </param>/// <returns>The return value is the RGB value of the image point. If the specified pixel is outside the current clipping region, the return value is clr_invalid. </returns>[DllImport ("GDI32")] Public Static extern UINTGetPixel (IntPtr HDC,intNxpos,intNypos);

The x, y coordinates of the function we have acquired, but the device environment handle HDC How to get it, here we also use a WIN32 API function:GetDC.

The role of the GetDC function is to retrieve the handle of the display device context environment, the function prototype is HDC GetDC (HWND hwnd)

"Translation" is as follows:

/// <summary>///This function retrieves a handle to the display device context environment for a specified window's customer area or entire screen.///You can later use the handle in a GDI function to draw in the device context. /// </summary>/// <param name= "HWnd" >The device context is retrieved by the handle of the window, and if the value is NULL,GETDC, the device context for the entire screen is retrieved. </param>/// <returns>returns the device context for the specified window client area if successful, or null if it fails. </returns>[DllImport ("User32")] Public Static externIntPtr GetDC (IntPtr hWnd);

Because of the unmanaged code, we need to manually release the handle to the environment. Here's another API function:ReleaseDC
The function of the RELEASEDC function is to release the device context, the function prototype is INT ReleaseDC (HWND hwnd, HDC HDC)

"Translation" is as follows:

/// <summary>///This function frees the device context (DC) for use by other applications. The effect of a function is related to the device context type. ///it only releases the common and device context, which is not valid for classes or private ones. /// </summary>/// <param name= "HWnd" >A handle to the window that contains the device context environment that you want to release. </param>/// <param name= "HDC" >a handle to the device context environment to be freed. </param>/// <returns>If the release succeeds, the return value is 1, and if no success is released, the return value is 0. </returns>[DllImport ("User32")] Public Static extern intReleaseDC (IntPtr hWnd, IntPtr HDC);

Then we start writing the code.

The page layout is as follows:

The overall code is also very simple.

usingSystem;usingSystem.Drawing;usingSystem.Windows.Forms;usingJackyhelper;namespacegetcolor{ Public Partial classMainform:form {/// <summary>        ///displays a handle to the device context environment. /// </summary>        PrivateIntPtr _HDC =IntPtr.Zero; /// <summary>        ///a handle to the window. /// </summary>        Private ReadOnlyIntPtr _hwnd =IntPtr.Zero;  PublicMainForm () {InitializeComponent (); }        Private voidTimer1_Tick (Objectsender, EventArgs e) {System.Drawing.Point P=mouseposition; Tsslcursorpos.text=string. Format ("X:{0},y:{1}", p.x, P.Y); UINTcolor =Win32helper.getpixel (_HDC, p.x, P.Y); byteR =win32helper.getrvalue (color); byteg =win32helper.getgvalue (color); byteb =win32helper.getbvalue (color); Txtr.text=convert.tostring (R); Txtg.text=convert.tostring (g); Txtb.text=convert.tostring (b); Piccolor.backcolor=Color.FromArgb (R, G, b); Txthexcolor.text="#"+ r.tostring ("X"). PadLeft (2,'0') + g.tostring ("X"). PadLeft (2,'0') +b.tostring ("X"). PadLeft (2,'0'); }        /// <summary>        ///take the Color button to press/// </summary>        /// <param name= "Sender" ></param>        /// <param name= "E" ></param>        Private voidBtngetcolor_mousedown (Objectsender, MouseEventArgs e) {_HDC=Win32helper.getdc (_hwnd); Cursor=Cursors.cross; Timer1. Enabled=true; }        /// <summary>        ///take color button to release/// </summary>        /// <param name= "Sender" ></param>        /// <param name= "E" ></param>        Private voidBtngetcolor_mouseup (Objectsender, MouseEventArgs e)            {Win32helper.releasedc (_hwnd, _HDC); Cursor=Cursors.Default; Timer1. Enabled=false; Text="Color Picker by Jacky qq:773091523"; }    }}
        /// <summary>        ///2014-12-5 21:43:51///gets the red intensity value in an RGB color value. /// </summary>        /// <param name= "RGB" >the specified RGB color value. </param>        /// <returns></returns>         Public Static byteGetrvalue (UINTRGB) {            return(byte) RGB; }        /// <summary>        ///2014-12-5 21:51:24///gets the green intensity value in an RGB color value. /// </summary>        /// <param name= "RGB" >the specified RGB color value. </param>        /// <returns></returns>         Public Static byteGetgvalue (UINTRGB) {            return(byte)(((ushort) (RGB)) >>8); }        /// <summary>        ///2014-12-5 21:52:37///gets the blue intensity value in an RGB color value. /// </summary>        /// <param name= "RGB" >the specified RGB color value. </param>        /// <returns></returns>         Public Static byteGetbvalue (UINTRGB) {            return(byte) (RGB >> -); }

Shortcomings, but also hope that the great God, I appreciate it.

C # Color Picker

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.