Search code examples
functionbackgroundvb6constantstopmost

VB6 - How to make the form second top most?


I used the following VB6 code,

Private 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
Private Const HWND_TOPMOST = -1
Private Const HWND_NOTOPMOST = -2
Private Const SWP_NOACTIVATE = &H10
Private Const SWP_SHOWWINDOW = &H40
Private Const SWP_NOMOVE = 2
Private Const SWP_NOSIZE = 1

Private Sub Form_Activate()
    Dim R As Long
    R = SetWindowPos(frmSlide.hwnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE Or SWP_NOSIZE)
End Sub

and the form is set with these properties,

   MaxButton       =   False
   MinButton       =   False
   ShowInTaskbar   =   False
   StartUpPosition =   CenterScreen
   WindowState     =   Maximized

This is to make the form go to the background. It did not go to the background. The idea here is to make the form only go one window back. For example: if the Notepad program window is open. This program only need to be in the background of Notepad and not other program windows. Is this possible?


Solution

  • I did some research based on Tarun Lalwani's information and this is what worked for me,

    Add a Timer to the form and use this code,

    Option Explicit
    
    Private Declare Function FindWindow1 Lib "User32" Alias "FindWindowA" (ByVal lpclassname As String, ByVal lpWindowName As String) As Long
    Private Declare Function SetWindowLong Lib "User32" Alias "SetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
    Private Const GWL_HWNDPARENT = -8
    
    Private parenthwnd As Long
    Private strTitle As String
    
    Public Function FindWindowHandle(Caption As String) As Long
      FindWindowHandle = FindWindow1(vbNullString, Caption)
    End Function
    
    Private Sub Form_Load()
        On Error Resume Next
        strTitle = "Untitled - Notepad"
    
        With Timer1
            .Interval = 2000
            .Enabled = True
        End With
    End Sub
    
    Private Sub Timer1_Timer()
        If FindWindowHandle(strTitle) <> 0 Then
            Timer1.Enabled = False
            parenthwnd = 0
            parenthwnd = FindWindow1(vbNullString, strTitle)
            Dim R As Long
            R = SetWindowLong(parenthwnd, GWL_HWNDPARENT, Me.hWnd)
        End If
    End Sub
    

    When the Notepad is openned it will be the parent to this form.

    Warning: I have set the form properties to these,

       MaxButton       =   False
       MinButton       =   False
       ShowInTaskbar   =   False
       StartUpPosition =   CenterScreen
       WindowState     =   Maximized
    

    If you set the same properties make sure you add a button or any other method to close the form. Otherwise the form will be on top and it may be difficult to close it.