4

I've been linked in the past to this response to a similar question on converting WPF pixel coordinates to desktop ones, however I'm not sure I understand the maths involved.

Astonish' answer states that "Pixels per WPF Unit = ConstantWPFUnit size * monitor DPI;" and that "The constant WPF unit size is 1/96."

In my case, I've taken the DPI from a graphics object which was created from the bitmap object (as I couldn't find the property the Astonish spoke of) that I created after taking a screenshot of the desktop, so I have:

Graphics g = Graphics.FromImage(bitmap);
float WpfUnit = (1 / 96) * g.DpiX;

Given that the DPI being returned from the graphics object is 96, I am left with

WpfUnit = (1 / 96) * 96 = 1

However, WpfUnit is coming out as 0 for some unknown (to me) reason. The only way I can see to fix this is to say

if(WpfUnit == 0) WpfUnit = 1;

And even that doesn't really fix the issue, as the height value and top values, when multiplied by the WpfUnit as suggested in the linked answer, have nothing done to them aside from being multiplied by 1.

So, in conclusion, I'm still stuck on converting WPF pixels to desktop pixels. Any help on this would be greatly appreciated.

Community
  • 1
  • 1

2 Answers2

6

WpfUnit is coming out as zero because it's doing integer math with the 1/96. Explicitly declare those numbers as floats.

Paul Sonier
  • 38,903
  • 3
  • 77
  • 117
2

How about built-in PointToScreen and PointFromScreen methods? Or am I missing something?

huseyint
  • 14,953
  • 15
  • 56
  • 78
  • I've looked at those two methods but they work with System.Windows.Point instead of the System.Drawing.Point which I need to create a rectangle object :( –  Jul 27 '09 at 17:34
  • You can always use Adapter Pattern to create wrappers from one type to another. See en.wikipedia.org/wiki/Adapter_pattern – huseyint Jul 27 '09 at 17:38
  • Thanks, again! I really hadn't thought of manually converting between the two :( –  Jul 27 '09 at 17:55
  • When you don't have any window you cannot use this approach. For more flexible scaling see: http://jerryclin.wordpress.com/2007/11/13/creating-non-rectangular-windows-with-interop/ the code includes the class for scaling. – greenoldman Oct 21 '10 at 08:07