CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 13 of 13

Thread: How to make a form ALWAYS ON TOP!

Threaded View

  1. #1
    Join Date
    Jun 2004

    How to make a form ALWAYS ON TOP!

        Const HWND_NOTOPMOST As Int32 = -2
        Const HWND_TOPMOST As Int32 = -1
        Const HWND_TOP As Int32 = 0
        Const HWND_BOTTOM As Int32 = 1
        Const SWP_NOSIZE As Int32 = 1
        Private Structure RECT
            Public rLeft, rTop, rRight, rBottom As Int32
        End Structure
        Private Declare Function apiGetTopWindow Lib "user32" Alias "GetTopWindow" (ByVal hWnd As Int32) As Int32
        Private Declare Function apiGetWindowRect Lib "user32" Alias "GetWindowRect" (ByVal hWnd As Int32, ByRef lpRect As RECT) As Boolean
        Private Declare Function apiSetWindowPos Lib "user32" Alias "SetWindowPos" (ByVal hWnd As Int32, ByVal hWndInsertAfter As Int32, ByVal X As Int32, ByVal Y As Int32, ByVal cx As Int32, ByVal cy As Int32, ByVal wFlags As Int32) As Boolean
        Private Declare Function apiLockWindowUpdate Lib "user32" Alias "LockWindowUpdate" (ByVal hWndLock As Int32) As Int32
        Private t As New Threading.Thread(AddressOf KeepOnTop)
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            t.Start() '''''''''''''''''''''''''''''Start thread to keep top most status
        End Sub
        Private Sub Form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
            t.Abort() ''''''''''''''''''''''''''''''''Abort keeping the window topmost
        End Sub
        Private Sub KeepOnTop()
            Dim hwnd As Int32, r As New RECT
                hwnd = Me.Handle.ToInt32
                apiLockWindowUpdate(0)'''''''''''''''''''''''''''Unlock any previous calls
                apiLockWindowUpdate(hwnd) ''''''''''''''''''''Lock the desktop from updating for a moment, so that tooltips dont get stranded
                If apiGetTopWindow(HWND_TOP) <> hwnd Then ''''If the topmost window is not the specified window
                    apiGetWindowRect(hwnd, r) ''''''''''''''''Get rectangular dimensions of the specified window
                    apiSetWindowPos(hwnd, HWND_TOPMOST, r.rLeft, r.rTop, 0, 0, SWP_NOSIZE) 'Set the specified window as the topmost
                    apiLockWindowUpdate(0) '''''''''''''''''''''''Unlock desktop so that it can update itself visually
                End If
                System.Threading.Thread.Sleep(1) '''''''''''''Sleep for the shortest period possible
        End Sub
    Last edited by TT(n); January 19th, 2008 at 02:47 AM. Reason: extra description

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

On-Demand Webinars (sponsored)