基本思路:
由于从DC中获取颜色的方法有一定的问题,有些情况下不能很好的支持。所以采用图像的方式。
1、从屏幕上获取屏幕的图像。
2、从图像上获取坐标点的颜色。
话不多说,直接上代码。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
timer1_Tick(sender, e);
}
[DllImport("gdi32.dll")]//取指定点颜色
private static extern int GetPixel(IntPtr hdc, Point p);
private void timer1_Tick(object sender, EventArgs e)
{
//把坐标显示到窗口上
Xvalue.Text = MousePosition.X.ToString();
Yvalue.Text = MousePosition.Y.ToString();
Size s = new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Bitmap memoryImage = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics memoryGraphics = Graphics.FromImage(memoryImage);
memoryGraphics.CopyFromScreen(0, 0, 0, 0, s);
Color cl = memoryImage.GetPixel(MousePosition.X, MousePosition.Y);
Colorvalue.Text = "#" + cl.R.ToString("X").PadLeft(2, '0') + cl.G.ToString("X").PadLeft(2, '0') + cl.B.ToString("X").PadLeft(2, '0');//输出16进制颜色
RGBvalue.Text = cl.R.ToString() + ',' + cl.G.ToString() + ',' + cl.B.ToString();//输出RGB
//设置颜色框
pictureBox1.BackColor = cl;
//pictureBox1.Image = memoryImage;
//ReleaseDC(IntPtr.Zero, hdc);
memoryGraphics.Dispose();
}
}