The title was supposed to be "Get that bloody pixel's color", but I guess the reason for that is that I somehow managed to spray coffee leftovers on the screen, keyboard & myself, the mouse got away.... Anyway the ARGB value of the coffee stain is 255,225,212,192:)
First thing, the reason:
A few days ago I needed to copy a certain color from the document into the app I'm developing. As usual the "color" was copied from a website by the "printscreen - crop - paste" method, which left me with the image and a customer saying "like this".
Digging a bit into the .NET I've found the easiest way would be to do a similar thing:
1. Capture the screen into an image.
2. Get the pixel corresponding to the mouse location
3. Display it's RGB values.
Easy said, and thanks to the M$ .NET team easy done.
The code for the 1st step is:
int w = Screen.PrimaryScreen.Bounds.Width;
int h = Screen.PrimaryScreen.Bounds.Height;
Bitmap img = new Bitmap(w, h);
Graphics g = Graphics.FromImage(img);
g.CopyFromScreen(new Point(0, 0), new Point(0, 0), new Size(w, h));
For the second step a call to the user32.dll is needed:
[System.Runtime.InteropServices.DllImport("user32")]
public static extern int GetCursorPos(out POINTAPI lpPoint);
public struct POINTAPI
{
public int x;
public int y;
}
And the actual code is:
POINTAPI tPOS;
GetCursorPos(out tPOS);
The 3rd step is the trivial step:
Color color = img.GetPixel(tPOS.x, tPOS.y);
label1.Text = color.A.ToString() + ":" + color.R.ToString() + ":" + color.G.ToString() + ":" + color.B.ToString();
I've wrapped it all in a timer's tick (laziness again...) The resulting method is:
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop();
POINTAPI tPOS;
GetCursorPos(out tPOS);
int w = Screen.PrimaryScreen.Bounds.Width;
int h = Screen.PrimaryScreen.Bounds.Height;
Bitmap img = new Bitmap(w, h);
Graphics g = Graphics.FromImage(img);
g.CopyFromScreen(new Point(0, 0), new Point(0, 0), new Size(w, h));
Color color = img.GetPixel(tPOS.x, tPOS.y);
label1.Text = color.A.ToString() + ":" + color.R.ToString() + ":" + color.G.ToString() + ":" + color.B.ToString();
label1.ForeColor = color;
System.Threading.Thread.Sleep(1);
timer1.Start();
}
This code works, though the screen capturing is a bit consuming in CPU terms.
Monday, October 12, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment