我希望能够确定屏幕上某一点的winform背景颜色,以便根据该特定颜色采取一些操作。不幸的是,System.Drawing库似乎没有指定可以实现此操作的方法。
那么我应该如何确定某一点的颜色呢?
请使用以下方法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing;
namespace ColorUnderCursor
{
class CursorColor
{
[DllImport("gdi32")]
public static extern uint GetPixel(IntPtr hDC, int XPos, int YPos);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool GetCursorPos(out POINT pt);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr GetWindowDC(IntPtr hWnd);
/// <summary>
/// Gets the System.Drawing.Color from under the mouse cursor.
/// </summary>
/// <returns>The color value.</returns>
public static Color Get()
{
IntPtr dc = GetWindowDC(IntPtr.Zero);
POINT p;
GetCursorPos(out p);
long color = GetPixel(dc, p.X, p.Y);
Color cc = Color.FromArgb((int)color);
return Color.FromArgb(cc.B, cc.G, cc.R);
}
}
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int X;
public int Y;
public POINT(int x, int y)
{
X = x;
Y = y;
}
}
}
Graphics.CopyFromScreen()
將屏幕內容繪製到一個Bitmap
對象中。從那裡,您只需要使用Bitmap.GetPixel()
來檢索具有正確顏色的Color
對象。
以下是可用於檢索完整桌面(可與多個顯示器一起使用)的代碼:
public Image GetScreenshot()
{
int screenWidth = Convert.ToInt32(System.Windows.SystemParameters.VirtualScreenWidth);
int screenHeight = Convert.ToInt32(SystemParameters.VirtualScreenHeight);
int screenLeft = Convert.ToInt32(SystemParameters.VirtualScreenLeft);
int screenTop = Convert.ToInt32(SystemParameters.VirtualScreenTop);
Image imgScreen = new Bitmap(screenWidth, screenHeight);
using (Bitmap bmp = new Bitmap(screenWidth, screenHeight, PixelFormat.Format32bppArgb))
using (Graphics g = Graphics.FromImage(bmp))
using (Graphics gr = Graphics.FromImage(imgScreen))
{
g.CopyFromScreen(screenLeft, screenTop, 0, 0, new Size(screenWidth, screenHeight));
gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
gr.DrawImage(bmp, new Rectangle(0, 0, screenWidth, screenHeight));
}
return imgScreen;
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing;
class CursorHue
{
[DllImport("gdi32")]
public static extern uint GetPixel(IntPtr hDC, int XPos, int YPos);
public static float GetHue(Point p)
{
long color = GetPixel(dc, p.X, p.Y);
Color cc = Color.FromArgb((int)color);
return cc.GetHue();
}
}
public static bool AreSimilar(Color c1, Color c2, float tolerance = 15f)
{
return Math.Abs(c1.GetHue() - c2.GetHue() <= tolerance;
}