How to get color data of a pixel when DPI is > 100%

Dec 25 2017 5:15 PM
So I have a program with 2 forms. The first form opens a small dialog in which the user can select a color from anywhere on the screen when a key is pressed. The code for this is below and it works perfectly, WHEN DPI IS SET TO 100%.
My issue is that I have a QHD screen on my laptop. If I set my DPI to 100%, everything becomes microscopic. So, since I am primarily developing this program for myself, I would like it to work with different DPIs. Ideally it would work with any DPI, that way the program is portable and I can distribute it.
The code is below. On a keypress, a bitmap of the desktop is created, and the color or the pixel under the cursor's current location is stored into a color variable. Again it works very well with 100% dpi, but gives only black/white colors when dpi is different. I've tried setting AutoScale mode to DPI, Font, and None, but the results did not change.
I've been researching this issue for 3 days but I cannot find a solution.
Thanks for your time!
  1. private void PixelColor_KeyDown(object sender, KeyEventArgs e)  
  2. {  
  3.          Point cursor = new Point();  
  4.          cursor.X = Cursor.Position.X;  
  5.          cursor.Y = Cursor.Position.Y;  
  6.          Color c = GetColorAt(cursor);  
  7.          this.BackColor = c;  
  8. }  
  10. Bitmap screenPixel = new Bitmap(1, 1, PixelFormat.Format32bppArgb);  
  11. public Color GetColorAt(Point location)  
  12. {  
  13.          using (Graphics gdest = Graphics.FromImage(screenPixel))  
  14.          {  
  15.             using (Graphics gsrc = Graphics.FromHwnd(IntPtr.Zero))  
  16.             {  
  17.                   IntPtr hSrcDC = gsrc.GetHdc();  
  18.                   IntPtr hDC = gdest.GetHdc();  
  19.                   int retval = BitBlt(hDC, 0, 0, 1, 1, hSrcDC, location.X, location.Y,                   (int)CopyPixelOperation.SourceCopy);  
  20.                   gdest.ReleaseHdc();  
  21.                   gsrc.ReleaseHdc();  
  22.             }  
  23.          }  
  24.       return screenPixel.GetPixel(0, 0);  
  25. }

Brought to you by:

Answers (1)