How to get pixel correctly, when Windows Magnifier is on?

Jacob Mordon 225 Reputation points
2024-11-12T07:51:34.3033333+00:00

Hi, I would like to know, if there's some way to get correctly pixel color, which is pointed by cursor, when Windows Magnifier is on?

This is code sample, which works perfectly whether magnifier is off:

public static Color GetColorAtPosition(int x, int y)
{
	var desk = PInvoke.GetDesktopWindow();
	var dc = PInvoke.GetWindowDC(desk);
	try
	{
	    var a = (int)PInvoke.GetPixel(dc, x, y).Value;
	    return Color.FromArgb(255, (byte)(a >> 0 & 0xff), (byte)(a >> 8 & 0xff), (byte)(a >> 16 & 0xff));
	}
	finally
	{
	    PInvoke.ReleaseDC(desk, dc);
	}
}

P.S. PInvoke was created using Microsoft.Windows.CsWin32

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,053 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Jiale Xue - MSFT 46,801 Reputation points Microsoft Vendor
    2024-11-12T09:40:50.0433333+00:00

    Hi @Jacob Mordon , Welcome to Microsoft Q&A,

    Get the exact pixel color by taking a screenshot and locating the mouse position in the image. This method avoids the interference of the magnifying glass.

    Here is a sample code:

    using System.Drawing;
    
    public static Color GetColorAtPosition(int x, int y)
    {
        using (var bitmap = new Bitmap(1, 1))
        {
            using (var g = Graphics.FromImage(bitmap))
            {
                g.CopyFromScreen(x, y, 0, 0, new Size(1, 1));
            }
            return bitmap.GetPixel(0, 0);
        }
    }
    

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.