csammisrun

A rare situation

VB trickery: Displaying modeless windows over modal windows

without comments

While browsing Raymond Chen’s blog, as I’m prone to doing, I discovered a series of articles on the subject of modality. This had been something of a thorn in my side recently, because one of the things that VB doesn’t allow a developer to do is display a modeless window over a modal one. Some might say there’s a good reason for that, but what’s life without breaking a few unwritten rules?

Say you have a window situation like the one pictured below. The parent window created a child window and called the “Form.Show vbModal” method to display it relative to itself.

+----------------------------------------------------------+
|  Parent (inactive)                                       |
+----------------------------------------------------------+
|                                                          |
|                                                          |
|         +------------------------------------------+     |
|         |  Modal Child (active)                    |     |
|         +------------------------------------------+     |
|         |                                          |     |
|         |           blah blah blah blah blah       |     |
|         |                                          |     |
|         |              |     OK       |            |     |
|         |                                          |     |
|         +------------------------------------------+     |
|                                                          |
|                                                          |
+----------------------------------------------------------+

Now imagine that the child attempted to display a modeless window of its own by creating a child window and displaying it relative to itself by calling “Form.Show” with no modality arguments. VB will throw a runtime error…well that’s no good.

To solve this problem, I adapted a idea put forth in one of Raymond’s articles. Instead of displaying the child window with vbModal, the parent displays it modelessly. The child takes the responsibility for calling “Form.Enabled = false” on the parent in its Form_Load event and calling “Form.Enabled = true” on the parent in its Form_Unload event. By shifting the modality responsibility to the child, the parent-child relationship appears normally to the user, but VB doesn’t know that the child form is UI-modal and thus doesn’t throw an exception when the child creates its own modeless windows.

One might ask me, and legitimately so, what possible reason could I have for wanting to do this? Because I wanted to has always been a good reason for doing the development things I do, so we’ll go with that :)

Written by Chris

November 10th, 2006 at 10:22 am

Posted in Development, General

Leave a Reply