确定一个像素的颜色在一个WinForms应用程序应用程序、像素、颜色、WinForms

2023-09-08 09:11:18 作者:莪的心好冷

我希望能够确定在某一个点在屏幕上的winform的backgroundColor,这样我就可以采取一些行动,具体取决于特定的颜色。可悲的是System.Drawing中图书馆似乎并没有指定一个方法,让我这样做。

I'd like to be able to determine the backgroundcolor of a winform at a certain point on the screen, so I can take some action depending on that particular color. Sadly the System.Drawing library doesn't seem to specify a method that enables me to do so.

我应该如何再在某一点决定了颜色?

How should I then determine the color at a certain point?

推荐答案

使用的:

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;
        } 
    }
}