运行效果截图:
后台代码:
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、Bint blue;int green;int red;//指定设备环境(句柄为0则为桌面)int hD;//颜色信息int c;//鼠标所在处坐标点int a;int b;#endregionpublic 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);//释放DCReleaseDC(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}
}