Example Application: The Color Selector
Microsoft Windows provides a function used to get a color stored in a pixel. The .NET Framework supports this operation in the Bitmap class, which is…
2 min read371 words
Introduction#
Windows includes built-in functionality to identify the color value of any specific pixel. In the .NET Framework, this is handled by the Bitmap class via the GetPixel method, which allows you to extract color data from any point in an image. Project: Building the Application
- Start Microsoft Visual Studio
- To create a new program, on the main menu, click File -> New Project...
- In the middle list, click Windows Application
- Set the Name to ColorSelector1 and click OK
- Copy the following picture and paste it somewhere in your computer
- 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
- Right-click the form and click View Code
- Above the public Form1() line, declare a Boolean variable named IsSelecting : using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace ColorSelector1 { public partial class Form1 : Form { bool isSelecting; public Form1() { InitializeComponent(); } } }
- Return to the form and double-click an unoccupied area of its body
- Implement the event as follows: private void Form1_Load(object sender, EventArgs e) { isSelecting = false; }
- Return to the form and click the picture box control on it
- In the Properties window, click the Events button and double-click MouseDown
- Implement the event as follows: private void pbxColor_MouseDown(object sender, MouseEventArgs e) { isSelecting = true; }
- Return to the form and click the picture box control on it
- In the Events section of the Properties window, double-click MouseUp and implement the event as follows: private void pbxColor_MouseUp(object sender, MouseEventArgs e) { isSelecting = false; }
- Return to the form and click the picture box control on it
- In the Events section of the Properties window, double-click MouseMove and implement the event as follows: private void pbxColor_MouseMove(object sender, MouseEventArgs e) { if (isSelecting == true) { Bitmap bmpImage = (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; } }
- Execute the application
- Click the mouse on the picture mouse and drag to produce a color
- Close the form
Main Copyright © 2010-2011 C# Key

