How to Create a Modeless Dialog or Form in Visual Basic

ID: Q114775


The information in this article applies to:


SUMMARY

This article contains information on how to create a modeless dialog or form in Visual Basic. An example of a modeless dialog is the toolbar in Microsoft Excel version 5.0 and Word version 6.0. A modeless form always displays on top of the parent form, but is not bounded by the parent form nor does it stay on top of all other applications as does SetWindowPos and HWND_TOPMOST.

For additional information on SetWindowPos, please see the following article in the Microsoft Knowledge Base:

Q84251 : How to Create a Topmost or Floating Window in Visual Basic


MORE INFORMATION

The Windows API SetWindowWord() is used with the value GWW_HWNDPARENT to change the parent of the form that you want to be a modeless dialog. SetWindowWord returns the original parent's window handle that we need to restore when the form is unloaded to avoid a General Protection Fault.

Step-by-Step Example

  1. Start a new project in Visual Basic. Form1 is created by default.


  2. Add a second form (Form2) to the project.


  3. Add a the following code to the Form_Load event for Form1:
    
       Sub Form_Load()
          Form2.Show      'display the child form
          Form1.Caption = "Parent"
          Form2.Caption = "Child"
       End Sub
     


  4. Add the following declarations to the general section of Form2:
    
       ' Enter the following Declare statement as one, single line:
       Declare Function SetWindowWord Lib "User" (ByVal hwnd As Integer,
          ByVal Index As Integer, ByVal wNewWord As Integer) As Integer
       Const GWW_HWNDPARENT = (-8)
       Dim OriginalParenthWnd As Integer
     


  5. Add the following code the Form_Load event of Form2:
    
       Sub Form_Load()
    
        ' Set parent for the toolbar to display on top of:
        OriginalParenthWnd = SetWindowWord(Me.hWnd, GWW_HWNDPARENT, Form1.hWnd)
    
        Me.Width = Form1.Width \ 3      ' Scale child form
        Me.Height = Form1.Height \ 3
    
       End Sub
     


  6. Add the following code the Form_Unload event of Form2:
    
       Sub Form_Unload()
    
         Dim ret As Integer
    
         ' Return the original parent handle to avoid a GP Fault
         ret = SetWindowWord(Me.hWnd, GWW_HWNDPARENT, OriginalParenthWnd)
    
       End Sub
     


  7. Press the F5 key to run the program. The child form is displayed as a modeless dialog of the parent form.


Additional query words: 2.00 3.00


Keywords          : 
Version           : 
Platform          : 
Issue type        : 

Last Reviewed: June 10, 1999