运行效果截图:
后台代码:
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;
using System.Runtime.InteropServices;
namespace ColorPicker
{
public partial class ColorPickerSimple : Form
{
#region 引入外部方法
//GetDC,获取DC(设备环境)
[DllImport("user32", ExactSpelling = true, CharSet = CharSet.Ansi, SetLastError = true)]
private static extern int GetDC(int hwnd);
//GetPixel,获取像素点
[DllImport("gdi32", ExactSpelling = true, CharSet = CharSet.Ansi, SetLastError = true)]
private static extern int GetPixel(int hdc, int X, int y);
//ReleaseDC,释放DC
[DllImport("user32", ExactSpelling = true, CharSet = CharSet.Ansi, SetLastError = true)] //确定坐标
private static extern int ReleaseDC(int hwnd, int hdc);
#endregion
#region 字段
//R、G、B
int blue;
int green;
int red;
//指定设备环境(句柄为0则为桌面)
int hD;
//颜色信息
int c;
//鼠标所在处坐标点
int a;
int b;
#endregion
public ColorPickerSimple()
{
InitializeComponent();
}
#region 窗体事件
/// <summary>
/// 窗体加载
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ColorPickerSimple_Load(object sender, EventArgs e)
{
txtR.ReadOnly = true;
txtG.ReadOnly = true;
txtB.ReadOnly = true;
txtColor.ReadOnly = true;
timer1.Enabled = true;
}
#endregion
#region 获取颜色
/// <summary>
/// Timer事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void timer1_Tick(object sender, EventArgs e)
{
//获取鼠标所在处的坐标
a = System.Windows.Forms.Control.MousePosition.X;
b = System.Windows.Forms.Control.MousePosition.Y;
//获取DC,设备环境(桌面)
hD = GetDC(0);
//获取颜色值
c = GetPixel(hD, a, b);
//释放DC
ReleaseDC(0, hD);
//由颜色值计算R、G、B值
red = c % 256;
green = (c / 256) % 256;
blue = (c / 256 / 256) % 256;
//显示颜色分值
txtR.Text = Convert.ToString(red);
txtG.Text = Convert.ToString(green);
txtB.Text = Convert.ToString(blue);
//显示拾取的颜色
Color color = Color.FromArgb(red, green, blue);
txtColor.BackColor = color;
}
#endregion
}
}