How To Create a Form That Always Stays on Top
Symptoms
Microsoft Visual Basic does not offer a property or method to make a formthe topmost window. This behavior can be achieved using the SetWindowPosWin32 API.
This article demonstrates how to set a form as the topmost window using theSetWindowPos Win32 API.
Resolution
The sample code below uses a function called SetTopMostWindow. TheSetTopMostWindow function sets a window as a topmost Window or as a normalWindow, based on the two parameters, hwnd and Topmost, passed to it.
The hwnd parameter specifies the handle of the window to be set as topmostor as normal.
The Topmost parameter specifies whether to set the form as topmost or asnormal. If the value is true, the function sets the form to always remainon top. If the value is false, the function sets the form as a normalwindow.
Step-by-Step ExampleStart a new Standard EXE project. Form1 is created by default.Add two command buttons (Command1 and Command2) to Form1.Set the caption property of Command1 to “Always on top.”Set the caption property of Command2 to “Normal.”Put the following code in the Form1 Declaration section:
Option ExplicitPrivate Sub Command1_Click()Dim lR As LonglR = SetTopMostWindow(Form1.hwnd, True)End SubPrivate Sub Command2_Click()Dim lR As LonglR = SetTopMostWindow(Form1.hwnd, False)End Sub On the Project menu, click Add Module, to add a new module to theproject.Add the following code to the new module:
Option ExplicitPublic Const SWP_NOMOVE = 2Public Const SWP_NOSIZE = 1Public Const FLAGS = SWP_NOMOVE Or SWP_NOSIZEPublic Const HWND_TOPMOST = -1Public Const HWND_NOTOPMOST = -2Declare Function SetWindowPos Lib “user32″ Alias “SetWindowPos”_(ByVal hwnd As Long, _ByVal hWndInsertAfter As Long, _ByVal x As Long, _ByVal y As Long, _ByVal cx As Long, _ByVal cy As Long, _ByVal wFlags As Long) As LongPublic Function SetTopMostWindow(hwnd As Long, Topmost As Boolean) _As LongIf Topmost = True Then ‘Make the window topmostSetTopMostWindow = SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, _0, FLAGS)ElseSetTopMostWindow = SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, _0, 0,FLAGS)SetTopMostWindow = FalseEnd IfEnd Function
NOTE: In the above sample code, an underscore (_) at the end of a line isused as a line-continuation character.
Press F5 to run the project.If you click the “Always on top” command button, your form becomes thetopmost window and remains on top of every window; you cannot move anyother window on top of it. If you click the “Normal” button, the formbehaves normally (you can move other windows on top of it).

Leave a Reply