AccessibleObjectFromPoint and per-monitor DPI - windows

I'm using accessibility with the AccessibleObjectFromPoint function, and I'd like it to work correctly on a per-monitor DPI environment. Unfortunately, I can't get it to work. I tried many things, and the situation for now is:
My app is marked as per-monitor-DPI-aware in the manifest. (True/PM)
I use GetCursorPos and then AccessibleObjectFromPoint.
How can the problem be reproduced:
Have two monitors, one with 100% DPI, the other with 125%.
Run Chrome on the 125% monitor.
Use AccessibleObjectFromPoint on one of the tab names, it won't work.
It works with some apps (DPI-aware, it seems, like explorer), but doesn't work with others. I tried several relevant functions, such as GetPhysicalCursorPos and PhysicalToLogicalPointForPerMonitorDPI, but nothing works.
It's worth noting that Microsoft's inspect.exe works as expected.

I’ve been struggling with this exact same problem for several weeks and can now tell you my findings. Unfortunately I can’t give you more than a hint of code, because the project I am working on, is proprietary.
The issue started at Windows 8.1. The problem did not exist on Windows 7 or Vista, because AccessibleObjectFromPoint always used raw physical coordinates, as documented here: https://msdn.microsoft.com/en-us/library/windows/desktop/dd317984(v=vs.85).aspx .
“Microsoft Active Accessibility does not use logical coordinates. The following methods and functions either return physical coordinates or take them as parameters.” This has not been true since Windows 8.1.
AccessibleObjectFromPoint now uses a flawed calculation that cannot always find the correct window for reasons similar to my question here: High DPI scaling, mouse hooks and WindowFromPoint .
My findings lead me to one conclusion: The API is broken. This does not mean it is not possible though.
Possible solutions I have partially tested that seem to work follow.
Prerequisites are that you
1/. Make your process per monitor DPI aware, NOT USING THE MANIFEST (more on that later).
2/. Determine the hWnd of the window you want to query (WindowFromPoint() variants)
3/. Determine the monitor DPI of the queried hWnd
4/. Determine the DPI of your process
5/. Determine the DPI of the queried hWnd
6/. Determine the monitor origin and offset for the queried hWnd (MonitorFromWindow() and GetMonitorInfo() )
Next, depends on your platform
Windows 10.0.14393+
Write a function that finds the IAccessible (AccessibleObjectFromWindow() ) from the top level window, and then recursively call IAccessible::accHitTest until you reach the bottom-most IAccessible and perhaps ChildID data. Return that as if you would call AccessibleObjectFromPoint.
To call it successfully, you will need to scale the (x,y) co-ordinates into the scale system of the queried hWnd, using the DPIs and co-ordinates fetched in the list above. Watch out for systems where monitors are not the same size or if monitors are partially offset, or above and below.
And now for the important part for 10.0.14393 – Set your thread to the same DPI_AWARENESS_CONTEXT of the hWnd you are querying. Now call your new function. Now revert your thread to monitor DPI aware, and voila, it works, even if the window is not maximised. This is why you must not use the manifest.
If you are on Windows 8.1 to 10.0.10586 you have a tougher task.
Instead of calling accHitTest, as above, you have to recursively call AccessibleChildren and iterate the call IAccessible::accLocation to determine if your test point is within each child. This is tricky and starts to get really messy when you get to e.g. combo boxes in products like Office, which is only system DPI aware.
That’s all I can give you for now.
To do it successfully on multi-platform (mine has to work from Vista to Windows-Current) the only really safe bet is to write a wrapper DLL in C++ that can determine at runtime which OS it is on and change code path accordingly. The reason you want to do it in C++ is to avoid passing IAccessible objects across the .Net/unmanaged marshalling boundary. You can call IUnknown::Release on objects you don’t need to return n the unmanaged side. You can do it all in .Net, but it will be slow.
P.S. also watch out for Chrome returning infinite trees where parents are children of their parents, some snity checks are required. Also, Chrome does not return accRole correctly, and will give you HTML tags instead of VT_I4.
Good luck

A fairly workable solution is as follows, in your IAccessible recursive function:
Use getwindowrect to capture the physical right on main window
Use accChild.accLocation in loop to capture left and Width on each Object
Add this simple test
If l > rct2r.Right And l > arrIACC.x2 Then
arrIACC.x2 = l + w
End If
if dpi = 100 then no Object is furter out than physical right
if dpi > 100 then closebutton is...x pix offset
Use the difference to rescale all values you are in use of Width
arrIACC.w1 = CInt(((-rct2r.Left + arrIACC.w1) / arrIACC.x2) * rct2r.Right)
This solution is from an Excel plugin I have developed, I was testing the Width of the quick access toolbar qat and my result was +- 5 pixels regardless of any DPI.

Related

How to set DPI scale to less than 100% on Windows 10 - With multiple displays

So I have a big 32 inch display with a resolution of 1440p, and I want to set the DPI scaling to 75% instead of 100%. But I can't find any way to do so on multiple monitors.
I currently have:
Display 1 [2560 x 1440] (Main display I want to change)
Display 2 [2560 x 1440] (This one is 27 inches so it's fine as is)
Display 3 [3840 x 2160] (Set to 100%, fine as it is)
This trick (click me) changes DPI scaling via some registry keys (LogPixels & Win8DpiScaling), but when I use that trick it downscales display 3 instead of display 1.
Is there a way to get this to work? I see no reason for Microsoft to limit the scaling in displays.
Note: I have a 2070 super, all the displays are plugged into the GPU via displayport directly, with the latest avalible firmware at the time of writing (september 2021)
The tl;dr:
Technical limitations aside, there are very solid user experience reasons why this probably isn't allowed.
No, Windows will not let you set UI scaling below 100%.
(even if a stable workaround were to be discovered, most users would probably be quite unhappy with the results)
While I would love¹ to be proven incorrect, the implications of scaling at less than 100% are so fraught that this limitation is unlikely to change in the near future.
Background:
This has been the case for ages, likely since Windows first introduced the feature.
Compatibility with current software
The only ~purely technical~ reason I can think of:
The 100% scaling size likely uses the smallest base image (e.g. Explorer and Taskbar icons, mouse and text cursors) resources included in various existing Microsoft and 3rd-party applications.
User experience
Going below the 100% point may cause small UI text and icons, especially in application toolbars and the Taskbar to be blurred to the point of ambiguity.
Those fine lines in the taskbar 'Windows' menu icon? Blurred or gone.
Taken to the extreme, the UI ~might~ become so unreadable that the user is effectively prevented from being able to read the text even in the 'Settings' window and therefore is 'stuck': i.e. not able to navigate through 'Settings' to restore the original '100%' scaling mode.
(Luckily, Windows is never used to run any SCADA software where confusing two icons could theoretically cost money or lives.)
Performance:
Since those carefully-designed graphic assets don't exist, if sub-100% scaling were allowed, it would also likely cause extra CPU/GPU workload - that is why only certain fixed sizes of up-sampling are shown on the normal Display settings screen and why the Advanced scaling settings screen warns that custom scaling between 100-500% is "not recommended".
That might also apply to any fixed scaling option offered below 100%, and absolutely would for custom scaling sizes.
Some people enjoy reading:
Vector-based TrueType/OpenType fonts usually contain a ~lot~ of manual tweaking / hints to enable readable display of very small point sizes.
The marketing department & friends of the C-suite
Could they implement this at a limited range of options? 90%? 75%?
Perhaps - but it's extra testing for a horrible-looking edge case.
The existence of the option, even if only available as a registry hack, might cause some people to actually use it in kiosks and other public-facing displays; this risks the same sort of bad PR as when a BSOD is seen on the 'arrivals' screen at a train station or airport monitor.
Combined with the first example below, even a 90% option could cause trouble in some environments.
Example and tutorial:
Imagine how Windows might look displayed on one of those cheapo '1080p-supported' projectors that actually only contains an imager with a native pixel resolution of, say, 1024x576 (or even 480x234).
Windows thinks it can send 1080p, since that what the HDMI connection advertises, so it does: any text / vector content looks atrocious.
(At least in this case the user could normally² unplug the projector and reconnect to a normal monitor to restore functionality.)
See for yourself... while connected to any monitor (at that monitor's native resolution), with Windows set to 100% scaling:
Open Windows Notepad
Type or paste in any block of text
Now, use the Zoom Out command from the View menu³ five or more times in a row
While not an exact analogue, you may still see how hard it could be to read down-sampled text, even when very high-contrast (the best-case scenario).
   ¹: As someone currently typing this very answer on a 1080p connection to a 55" 4K television as a second monitor, I came across the question very much hoping this was possible. Sadly, logic intervened and killed my potential joy.
   ²: Unless the computer is actually stored somewhere locked or inaccessible, such as a NUC-style PC hidden above the false ceiling in a conference room.
   ³: Alternatively, press <CTRL>-<Minus> five or more times.

WM_DPICHANGED suggested size is not scaled

The RECT I get from WM_DPICHANGED is not scaled when I move a window between two monitors with different scaling, I get the same dimensions in pixels whichever monitor I move it to (which results in the window being too large for the monitor or too small for its contents). From using Spy++ it looks like this is the case for other applications too. The documentation
suggests that it should be scaled linearly with DPI by default.
My application is using Qt Quick, which sets PROCESS_PER_MONITOR_DPI_AWARE by default. I've also tried SetProcessDpiAwareness(PROCESS_SYSTEM_DPI_AWARE) in my own code, which works as I want in terms of window sizing, but the contents are blurry on the secondary monitor (as you'd expect), and SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2) which works like the Qt default but scales the window decorations correctly too. In all 3 cases the window contents are scaled correctly.
I'm wondering if there is an issue with Windows itself, or if an update has changed this behaviour, as no application currently resizes correctly for me, and I'm pretty sure some applications, e.g. Explorer and Edge used to at least. I'm currently using Windows 10 17134.

Matlab GUI Compatibility Between Mac and Windows (Display)

For some time now, I've been working on a series of GUIs. I use a Mac running OSX to write all of my code, and the problem I've encountered is that it there are deviations in appearance when the GUIs are used in windows, some of which are minor, and some of which are very significant.
1) The text in the windows version is substantially larger overall. This results in some of my button titles simply going off the button, or panel titles moving beyond the panel.
2) Axes appear to be different dimensions between Mac and Windows. i.e. An axis that appears square on my Mac will appear elongated or rectangular on windows, and vice versa.
3) Graphical displays are different. This is the real problem. Some of my GUIs use axes to display text and model chemical reaction animations. On the Mac, they look perfectly fine, but on the windows system, the sizing is completely off.
I've set all "Units" to "characters" as suggested by the Mathworks help page, and I do not specify any fonts to allow each system to use its default. I have however, specified font sizes, but apparently, 12 point font on windows appears very different from 12 point font on mac.
Are there any ways around these problems? I thought setting a specified font size and allowing for use of default fonts would fix this, but it hasn't, and I'm a little dry for ideas at this point.
Try working in 'pixels' or absolute size units instead of 'characters', and apply a scaling factor to your font sizes.
Setting 'Units' to 'characters' is probably the wrong way to go for portability, and could be the main cause of your display sizing issues. Which specific Matlab page recommended that you do so? Was it talking about cross-platform portability? The characters unit is very convenient to work with, but it is tied to the font metrics for the default system font. (See the doco for Units property at http://www.mathworks.com/help/matlab/ref/axes_props.html). That's going to differ between different operating systems. Working with 'pixels' or inches/centimeters/points, which are absolute, will probably give you more uniform results across operating systems.
And you're not wrong: OS X tends to display fonts of a given size on screen smaller than Windows does. (Generally; YMMV depending on your display DPI and system settings and other things.) For example, I run my terminals and text editors at 10 or 12 points in Windows, but 14 point or larger on Mac. So apply a scaling factor to the font sizes you set in your GUI. Figure out what looks good on Mac, and then scale it in your code to something like windows_font_size = floor(mac_font_size * 0.8) and see how it goes.
If you want to be more precise in scaling, you could grab the ScreenPixelsPerInch and ScreenSize root properties with get(0,...). You may also be able to call down in to Java code to get precise font metrics info to help with font scaling choices.
Either way, you're going to have to test your code on both systems instead of just expecting it to work portably. If you don't have ready access to a Windows development system, consider setting up a Windows VM on your Mac. With file sharing between the two sides, you'll be able to try your code out on both platforms right as you work with it.
I encountered this problem as well.
Calling this function within the FUNCTIONNAME_OpeningFcn might alleviate your issues:
function decreaseFontSizesIfReq(handles)
% make all fonts smaller on a non-mac-osx computer
persistent fontSizeDecreased
fontSizeDecreased = [];
if ~ismac()
% No MAC OSX detected; decrease font sizes
if isempty(fontSizeDecreased)
for afield = fieldnames(handles)'
afield = afield{1}; %#ok<FXSET>
try %#ok<TRYNC>
set(handles.(afield),'FontSize',get(handles.(afield),'FontSize')*0.75); % decrease font size
end
end
fontSizeDecreased=1; % do not perform this step again.
end
end

Windows XP/Vista/7 application that targets external monitor

I'm thinking to create a simple game that displays itself on the external monitor, if it's available.
I would be pleased to have this as simple as possible, in other words the programming handles the activation of the external monitor, and targets the gamewindow there automatically on start (by a commandline tool, api, ?). A mirror view would do fine as well.
Is this even possible? Would there be a good alternative, besides having (simpleminded) users having to set their monitor etc. by themselves?
I do not have a preferred language to work with; Java, C(++), C#, anything would do as long as it runs on Windows 7+.
Here are just a few examples of APIs related to multiple monitors / displays (pretty much, first relevant results of a Google search):
http://vb.mvps.org/articles/vsm20090302.pdf
http://www.codeproject.com/KB/system/multiplemonitor.aspx
http://www.realtimesoft.com/multimon/programming/
EnumDisplayMonitors will be a common point for most of these, the documentation of which is available at http://msdn.microsoft.com/en-us/library/dd162610%28VS.85%29.aspx :
The EnumDisplayMonitors function enumerates display monitors
(including invisible pseudo-monitors associated with the mirroring
drivers) that intersect a region formed by the intersection of a
specified clipping rectangle and the visible region of a device
context. EnumDisplayMonitors calls an application-defined
MonitorEnumProc callback function once for each monitor that is
enumerated. Note that GetSystemMetrics (SM_CMONITORS) counts only the
display monitors.
See also ChangeDisplaySettingsEx, which can be used to configure the displays, including "Position of the device in a multi-monitor configuration."

How can I resize my vb6 program so that it automatically fits in any screen resolution?

How can I have a vb6 program which opens correctly in 1280*1024 but when switched to other resolutions say 640*480 i can only see half of the screen. how to re-size my vb6 program so that it automatically fits in any screen resolution?
You need to use the Screen object, this will always give you the current resolution in pixels:
Dim screenwidth,screenheight As Single
screenwidth = Screen.Width \ Screen.TwipsPerPixelX
screenheight = Screen.Height \ Screen.TwipsPerPixelY
Usually a Form amenable to resizing has controls that lend themselves to a "flow" layout. Often this is something like a TextBox, grid control, etc. that supports scrollbars. You shrink/grow such controls as required after allocating positions for (i.e. moving) the fixed-size elements like buttons and such.
For a busy Form with lots of fixed size controls that isn't "document oriented" there is no set answer. Sometimes creating a scrollable Form makes sense but usually it doesn't.
Some people try to resize "fixed" elements, change fonts sizes, etc. This can produce results of mixed quality though, sometimes good and sometimes not.
Considerations about the Form size are best made up front as part of the design process. For some applications it might be better to decide on a minimum supported Form size. In other cases you may have to break things up with dialog Forms or tab controls.
There's no easy way to do this in VB6, like there is in .Net. You have to manually resize everything in the form's Resized event handler based on the new form's client size. It's a pain, and a huge mess, but it's the only way to do it.
Correction: There's never only one way to do things, but I've been programming VB6 for several years, and usually just writing it into the Resize handler is straightforward enough, and I haven't found any good way to do it other than that.
Have you tried any 3rd party tools for doing this? Here's (a free) one that seems to work :-
ActiveResize Control Lite - I created a quick project to try it and it does what it says on the tin!
The lite version has some limitions such as number of forms in project, number of controls on form etc. You can also buy a Standard or Professional version if you need more functionality.
I know we've spent countless hours trying to implement our own resizing code only to remove it all and fix the location of most controls, move a few to make it look better and limit the min/max functionality of the form - none of which give a nice user experience. If we needed to do it again I probably use this control (or a similar one) just for the time savings.
I use ComponentOne SizerOne
The C1Elastic control allow from resizing and maintain the aspect ratio, resizing the inside controls on the setting you defined.
It's not free, but it payed itself with all the time I saved.
Form1.Height = Screen.Height
Form1.Width = Screen.Width
This code sets form size according to screen resolution.
"ActiveResize Control Lite" ActiveX tool is limited to 20 controls per form.
Once we know the screen resolution, there are a number of things you can do.
• The easiest solution would be do design different form to accommodate the four most popular monitor resolutions – 640 x 480, 800 x 600, 1024 x 768, and 1600 x 1200.
• Alternatively, we could write code that dynamically resizes and relocates every control on the form, based on the screen resolution – not an easy undertaking!
• Third party controls that resize the controls based on the screen resolution are quite effective. On the whole, though, it's better to just avoid this kind of problem, if you can. For example, see Creating Flexible Forms in Visual Basic (Flexi-Forms) at codeguru.com
To auto fit screen resolution you need to download an active x, drag it on your conform.
Search for "veg gold vb6.0 screen Resize".

Resources