I'm trying to read a pixel from an external program and then get its RGB colors. This works flawlessly whenever I find the location with the mouse and extract the pixel colors. However when I try to do it from a console program, the RBG colors comes back.. differently than what I expected.
I believe it could be an offset missing, so whenever I find the location using my mouse it's using my screens pixel, and whenever I activate the external program using the function below it will take the pixel locations from that window handle.
It could also be something about it being a game, and it's getting drawn differently, any tips? If I try to get the pixel colors from notepad it works.
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr hWnd);
public static void Activate(string processName = "CookieGame")
{
var processes = Process.GetProcessesByName(processName);
var process = processes.FirstOrDefault();
if (process != null)
{
SetForegroundWindow(process.MainWindowHandle);
}
}
I use the following function for extracting pixel colors from a location, this is run after I've set the program as active window (function above):
public class MailReader
{
[DllImport("user32.dll")] public static extern bool GetCursorPos(ref Point lpPoint);
[DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] public static extern int BitBlt(IntPtr hDC, int x, int y, int nWidth, int nHeight, IntPtr hSrcDC, int xSrc, int ySrc, int dwRop);
static Bitmap screenPixel = new Bitmap(1, 1, PixelFormat.Format32bppArgb);
public static Color GetColorAt(Point location)
{
using (Graphics gdest = Graphics.FromImage(screenPixel))
{
using (Graphics gsrc = Graphics.FromHwnd(IntPtr.Zero)){
IntPtr hSrcDC = gsrc.GetHdc();
IntPtr hDC = gdest.GetHdc();
int retval = BitBlt(hDC, 0, 0, 1, 1, hSrcDC, location.X, location.Y, (int)CopyPixelOperation.SourceCopy);
gdest.ReleaseHdc();
gsrc.ReleaseHdc();
}
}
return screenPixel.GetPixel(0, 0);
}
}
Conole program being run, this returns the correct X and Y pixels that I told it to, but the colors come back off:
namespace TestProgram.TestConsole
{
class Program
{
static void Main(string[] args)
{
var model = new PixelInformation
{
X = 505,
Y = 27,
R = 117,
G = 208,
B = 50
};
var point = new Point();
point.X = model.X;
point.Y = model.Y;
ActivateWindow.Activate("cookieGame");
var location = PixelReader.GetColorAt(point);
Console.WriteLine("Position X: " + point.X + " Y: " + point.Y);
Console.WriteLine("R:" + location.R + " " + "G:" + location.G + " B:" + location.B);
Console.ReadKey();
}
}
}
These symptoms are consistent with your system using font scaling other than 100% and the process not being DPI aware. Thus the process is subject to DPI virtualization.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.