功能如标题,
演示如下:
源码如下:
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;
using System.Text.RegularExpressions;
namespace getPointColor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
[DllImport("user32.dll")]
static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("user32.dll")]
static extern Int32 ReleaseDC(IntPtr hwnd, IntPtr hdc);
[DllImport("gdi32.dll")]
static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos);
private void button1_Click(object sender, EventArgs e)
{
string pattern = @"^\d*$"; //判断输入为整数数值
string x = textBox1.Text;
if (x=="") {
MessageBox.Show("请输入X数值");
return;
}
if (!Regex.IsMatch(x, pattern)) {
MessageBox.Show("X坐标值应为整数");
return;
}
;
int x1 = int.Parse(x);
string y = textBox2.Text;
if (y == "")
{
MessageBox.Show("请输入Y值");
return;
}
if (!Regex.IsMatch(y, pattern))
{
MessageBox.Show("Y坐标值应为整数");
return;
}
int y1 = int.Parse(y);
//GetPixelColor(x, y);
Console.WriteLine(GetPixelColor(x1, y1));
Color color = GetPixelColor(x1, y1);
int red = color.R; //R值
int green = color.G; //G值
int blue = color.B; //B值
string cssvalue = System.Drawing.ColorTranslator.ToHtml(GetPixelColor(x1, y1)); //将颜色转换为CSS字符串
Type ty = color.GetType(); //获取color的type
textBox3.Text = "R:" + red.ToString() + " G:" + green.ToString() + " B:" + blue.ToString();
textBox4.Text = cssvalue;
MessageBox.Show("R:" + red.ToString() + " G:" + green.ToString() + " B:" + blue.ToString());
}
static public System.Drawing.Color GetPixelColor(int x, int y)
{
IntPtr hdc = GetDC(IntPtr.Zero);
uint pixel = GetPixel(hdc, x, y);
ReleaseDC(IntPtr.Zero, hdc);
Color color = Color.FromArgb((int)(pixel & 0x000000FF),
(int)(pixel & 0x0000FF00) >> 8,
(int)(pixel & 0x00FF0000) >> 16);
return color;
}
}
}
源码写得比较粗糙,请大佬勿喷,功能基本可以实现,分享给各位。