C# 获取实例中的像素颜色
我在本网站上搜索帖子时发现: 这种方法在尝试获取窗体内像素的颜色时仍然有效吗 如果不是,那么在2D颜色值数组中基本上“映射”窗体的方法是什么 例如,我有一个Tron游戏,我想检查lightbike的下一个位置是否已经包含另一个lightbike 谢谢,C# 获取实例中的像素颜色,c#,.net,graphics,pixel,C#,.net,Graphics,Pixel,我在本网站上搜索帖子时发现: 这种方法在尝试获取窗体内像素的颜色时仍然有效吗 如果不是,那么在2D颜色值数组中基本上“映射”窗体的方法是什么 例如,我有一个Tron游戏,我想检查lightbike的下一个位置是否已经包含另一个lightbike 谢谢, Ian您可以使用GetPixel方法获取颜色 e、 g //从图像文件创建位图对象。 位图myBitmap=新位图(“Grapes.jpg”) //获取myBitmap中像素的颜色。 Color pixelColor=myBitmap.GetP
Ian您可以使用GetPixel方法获取颜色 e、 g //从图像文件创建位图对象。 位图myBitmap=新位图(“Grapes.jpg”) //获取myBitmap中像素的颜色。 Color pixelColor=myBitmap.GetPixel(50,50) 这可能是另一种方法,可以针对不同的情况进行详细说明
您可以使用您引用的问题中的方法从窗体中获取像素的颜色,您只需首先确定像素是否在窗体的边界内,并且您需要将窗体中的坐标转换为屏幕坐标,反之亦然 编辑:经过一点思考,如果有人在表单顶部打开另一个窗口,这将是不好的!我想最好能想出一种不同的方法
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;
}
}
使用此选项,您可以执行以下操作:
public static class ControlExts
{
public static Color GetPixelColor(this Control c, int x, int y)
{
var screenCoords = c.PointToScreen(new Point(x, y));
return Win32.GetPixelColor(screenCoords.X, screenCoords.Y);
}
}
因此,在您的情况下,您可以:
var desiredColor = myForm.GetPixelColor(10,10);
使用此方法,是否有一种快速“截屏”当前实例的方法?有关截屏的信息我在“返回Win32”行中遇到问题。Visual Studio希望将其更改为Microsoft.Win32。我正在使用VisualStudio2010。有我必须导入的库吗?这个解决方案不干净。
IntPtr.Zero
将为您提供桌面dc,您的窗口顶部可能有窗口。更好:获取要从中获取颜色的控件的Handle
属性。
var desiredColor = myForm.GetPixelColor(10,10);