CodeItBetter Programming Another VB Programming Blog

How to set the form to Top of all other windows

Posted on August 22, 2009

In some instance, you may need to set your form on top of all other windows. To accomplish that, you can use the following sample code:

Instructions:

  • Create a new Project
  • Add a new form to it
  • Add a command button Command1

Now, Goto Form's code window and add the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Option Explicit
 
Declare Function SetWindowPos Lib "user32" (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 Long
Const HWND_TOPMOST = -1
Const HWND_NOTOPMOST = -2
Const SWP_NOACTIVATE = &H10
Const SWP_SHOWWINDOW = &H40
 
Sub AlwaysOnTop(formname As Form, SetOnTop As Boolean)
  If SetOnTop Then
    lFlag = HWND_TOPMOST
  Else
    lFlag = HWND_NOTOPMOST
  End If
  SetWindowPos formname.hwnd, lFlag, formname.Left / Screen.TwipsPerPixelX, formname.Top / Screen.TwipsPerPixelY, formname.Width / Screen.TwipsPerPixelX, formname.Height / Screen.TwipsPerPixelY, SWP_NOACTIVATE Or SWP_SHOWWINDOW
End Sub
 
Private Sub Form_Load()
  Command1.Caption = "Set Always on Top"
End Sub
 
Private Sub Command1_Click()
  'How to Call this fuction.
  AlwaysOnTop Me, True
End Sub
Comments (2) Trackbacks (0)
  1. The following give Compile Error Constants, fixed-length strings, arrays, user-defined types, and Declare statements not allowed as Public members of an object module
    Declare Function SetWindowPos Lib user32 (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 Long

  2. these source codes are very good


Reply

( Cancel )

 

Trackbacks are disabled.