Image of Navigational Panel mapped to Contents / Home / Search How to get a VB application 'on top of'
Tech Support Question

Image of Line Break

Q. I want my VB application continuously 'on top of', with a menu similar to the one in the windows clock. How do I do that?

Thanks in advance,

Ruben Biezeman
Email : rbiezema@inter.NL.net

A. Making you window stay on top of all other windows is not actually difficult, it requires only one API call and a few global constants - all of which can be obtained from the Windows API reference that ships with VB 3. The definitions are as below:

  Global Const HWND_TOPMOST = -1
  Global Const SWP_NOSIZE = &H1
  Global Const SWP_NOMOVE = &H2
  Global Const HWND_NOTOPMOST = -2
  Declare Sub SetWindowPos Lib "User" (ByVal hWnd As Integer, 
                                       ByVal hWndInsertAfter As Integer, 
                                       ByVal X As Integer, 
                                       ByVal Y As Integer, 
                                       ByVal cx As Integer, 
                                       ByVal cy As Integer, 
                                       ByVal wFlags As Integer)

This is a cool API call that can be used for all sorts of window manipulation; moving windows, sizing windows, and changing their relative position in the ZOrder (which windows are on top of which). In this case we do not want to adjust the size or position of the window, which we indicate by adding the NOSIZE and NOMOVE constants as the last parameter. This also means that we can just pass in zeros as the previous four parameters, as they will be ignored anyway. Of course the first parameter is the hWnd of the window that we want to affect.

To wrap all this up in a menu item, just like the Windows Clock, create a menu item with the caption 'Stay On Top' and the name mnuStayOnTop., then enter the following code in its click event:

  Sub mnuStayOnTop_Click
    If mnuStayOnTop.Checked = False then
      mnuStayOnTop.Checked = True
      SetWindowPos Me.hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE + 
                                                      SWP_NOSIZE
    Else
      mnuStayOnTop.Checked = False
      SetWindowPos Me.hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE + 
                                                        SWP_NOSIZE
    End If
  End Sub

This will also place a tick next to the menu item when the Window is staying on top.

This should achieve what you are after.


Image of Arrow to Previous Article Image of Arrow to Next Article

[TECH SUPPORT TOC]
Image of Line Break
[HOME] [TABLE OF CONTENTS] [SEARCH]