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!
- private void PixelColor_KeyDown(object sender, KeyEventArgs e)
- {
- Point cursor = new Point();
- cursor.X = Cursor.Position.X;
- cursor.Y = Cursor.Position.Y;
- Color c = GetColorAt(cursor);
- this.BackColor = c;
- }
-
- Bitmap screenPixel = new Bitmap(1, 1, PixelFormat.Format32bppArgb);
- public 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);
- }