Determine color of a pixel in a winforms application

前端 未结 3 1669
说谎
说谎 2021-01-06 15:16

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

3条回答
  •  一向
    一向 (楼主)
    2021-01-06 15:56

    Use that :

    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);
    
            ///  
            /// Gets the System.Drawing.Color from under the mouse cursor. 
            ///  
            /// The color value. 
            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;
            } 
        }
    }
    

提交回复
热议问题