Visualizing Hit Tests in a ContextMenu

Hit testing is the process of determining which visual entities are at a specific location on the screen, such as where the mouse cursor happens to be at the moment.  WPF has great support for hit testing, as explained here.

I often wonder what visual elements are at a specific location.  Keep in mind that in WPF multiple visual entities can occupy the same pixel, so you won’t necessarily see all of the occupants of that pixel.  I usually set up a hit test with a callback which dumps the type names of elements hit to the Output window.  Crude, I admit, but effective nonetheless.  It dawned on me today that I can display the result of a hit test in a ContextMenu instead!  For example:

A hit test is a hit test, of course, of course…

In the image seen above, you can see the effect of right-clicking on the chevron in the Expander.  The ContextMenu contains the Visuals encountered during a hit test of the cursor location when the mouse button was pressed.  What you cannot see in the screenshot above is that if you click on the visual representation of an element (a child menu item) then a Web browser will open and automatically perform a Google search for that type of element.

Here’s the code.   Since WordPress does not allow me to upload .ZIP files, after you download the file, change the extension from .DOC to .ZIP and then unzip it.  😉

Keep in mind that this is something I just threw together on a whim, so it might not function correctly in all situations.  If you find any bugs, please let me know.  As of now, I’m aware that the context menu does not show the result of a hit test in the ComboBox’s dropdown, instead it hits the Window’s content underneath.  I’m not sure what can be done about that yet…

Comments are closed.