Home

GDI+ Applications: Color Selector

   

Introduction

Each pixel on a monitor holds a certain color. If you want, you can get that color and use it however you want. The following application shows how to retrieve the color of a pixel based on its (x, y) coordinate.

Practical LearningPractical Learning: Creating the Application

  1. To create a new program, on the main menu, click File -> New -> Project...
  2. In the Templates list, click Windows Forms Application
  3. Set the Name to ColorSelector and click OK
  4. Copy the following picture and paste it somewhere in your computer
     
  5. Design the form as follows:
     
    Control Text Name Other Properties
    PictureBox   pbxColor Image: colorpal1.jpg
    Label Red:    
    TextBox   txtRed  
    Label Green:    
    TextBox   txtGreen  
    Label Blue:    
    TextBox   txtBlue  
    Panel   pnlPreview BorderStyle: FixedSingle
    Button Close btnClose  
  6. Right-click the form and click View Code
  7. In the body of the class, declare a Boolean variable named IsSelecting:
    private:
    		/// <summary>
    		/// Required designer variable.
    		/// </summary>
    		System::ComponentModel::Container ^components;
    		bool isSelecting;
  8. Return to the form and double-click an unoccupied area of its body
  9. Implement the event as follows:
    System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e)
    {
        isSelecting = false;
    }
  10. Return to the form and click the picture box control on it
  11. In the Properties window, click the Events button Events and double-click MouseDown
  12. Implement the event as follows:
    System::Void pbxColor_MouseDown(System::Object^  sender,
    			 System::Windows::Forms::MouseEventArgs^  e)
    {
        isSelecting = true;
    }
  13. Return to the form and click the picture box control on it
  14. In the Events section of the Properties window, double-click MouseUp and implement the event as follows:
    System::Void pbxColor_MouseUp(System::Object^  sender,
    			System::Windows::Forms::MouseEventArgs^  e)
    {
        isSelecting = false;
    }
  15. Return to the form and click the picture box control on it
  16. In the Events section of the Properties window, double-click MouseMove and implement the event as follows:
    System::Void pbxColor_MouseMove(System::Object^  sender,
    			 System::Windows::Forms::MouseEventArgs^  e)
    {
        if( isSelecting == true )
        {
    	 Bitmap ^ bmpImage = static_cast<Bitmap ^>(pbxColor->Image);
    	 Color clr = bmpImage->GetPixel(e->X, e->Y);
    
    	 txtRed->Text = clr.R.ToString();
    	 txtGreen->Text = clr.G.ToString();
    	 txtBlue->Text = clr.B.ToString();
    
    	 pnlPreview->BackColor = clr;
        }
    }
  17. Execute the application
  18. Click the mouse on the picture mouse and drag to produce a color
     
  19. Close the form
 

Home Copyright © 2007-2012 FunctionX