如何使用c#获取X,Y处像素的颜色?
至于结果,我可以将结果转换为我需要的颜色格式。我确信有一个API调用。
对于显示器上任何给定的X,Y,我想获得该像素的颜色。
从Pinvoke.net获取屏幕上的像素颜色:
using System;
using System.Drawing;
using System.Runtime.InteropServices;
sealed class Win32
{
[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);
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;
}
}
有一个Bitmap.GetPixel
的图像...是你所追求的?如果没有,你能说出你的x,y值吗?在控制?
请注意,如果您的意思是图像,并且想要获得大量像素,并且您不介意使用不安全的代码,那么Bitmap.LockBits
将比许多调用GetPixel
快得多。
除了P / Invoke解决方案之外,您还可以使用Graphics.CopyFromScreen将图像数据从屏幕获取到Graphics对象中。但是,如果您不担心可移植性,我会推荐P / Invoke解决方案。
对于WPF中的参考:(使用PointToScreen)
System.Windows.Point position = Mouse.GetPosition(lightningChartUltimate1);
if (lightningChartUltimate1.ViewXY.IsMouseOverGraphArea((int)position.X, (int)position.Y))
{
System.Windows.Point positionScreen = lightningChartUltimate1.PointToScreen(position);
Color color = WindowHelper.GetPixelColor((int)positionScreen.X, (int)positionScreen.Y);
Debug.Print(color.ToString());
...
...
public class WindowHelper
{
// ******************************************************************
[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);
static public System.Windows.Media.Color GetPixelColor(int x, int y)
{
IntPtr hdc = GetDC(IntPtr.Zero);
uint pixel = GetPixel(hdc, x, y);
ReleaseDC(IntPtr.Zero, hdc);
Color color = Color.FromRgb(
(byte)(pixel & 0x000000FF),
(byte)((pixel & 0x0000FF00) >> 8),
(byte)((pixel & 0x00FF0000) >> 16));
return color;
}
如果有人遇到这个问题并且没有一个解决方案正在工作,就像对我来说这样,而且你在WPF中,这就是我的工作方式:-)。
[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);
public static void getColor()
{
IntPtr hdc = GetDC(IntPtr.Zero);
uint pixel = GetPixel(hdc, Cursor.Position.X, Cursor.Position.Y);
ReleaseDC(IntPtr.Zero, hdc);
System.Drawing.Color color = System.Drawing.Color.FromArgb((int)pixel);
Console.WriteLine("Color is {0}", color);
}