Thursday, April 18, 2013

To Make your window form show as topmost window in VB.Net

In VB6 we used to use API function like :
Private Declare Function ShowWindow Lib "user32" (ByVal hwnd As Long, ByVal nCmdShow As Long) As Long

the equivalent function in .Net is something like:

<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function ShowWindow(ByVal hwnd As IntPtr, ByVal nCmdShow As  b      ShowWindowCommands) As Boolean
End Function

To make your window to topmost of your screen, there're a few simple steps to take:

  • Get your process ID when you call the program
Private Function GetProcessID() as Integer
    Dim ProcessProperties As New ProcessStartInfo
    ProcessProperties.FileName = "test.exe"
    ProcessProperties.Arguments = ""
    Dim myProcess As Process = Process.Start(ProcessProperties)
    Return myProcess.ID
End Function

  • Use the ProcessID to get window's Handle and set it to topmost

'SET API And variables
   <DllImport("user32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> _
Private Shared Function SetWindowPos(ByVal hWnd As IntPtr, ByVal hWndInsertAfter As IntPtr, ByVal X As Integer, ByVal Y As Integer, ByVal cx As Integer, ByVal cy As Integer, ByVal uFlags As Integer) As Boolean
    End Function

    Private Const SWP_NOSIZE As Integer = &H1
    Private Const SWP_NOMOVE As Integer = &H2

    Private Shared ReadOnly HWND_TOPMOST As New IntPtr(-1)
    Private Shared ReadOnly HWND_NOTOPMOST As New IntPtr(-2)

'Set  Window Pos to top most
  Public Shared Sub SwitchToProcess(ByVal PID As Integer)
        Dim hWnd As Integer
        hWnd = CType(System.Diagnostics.Process.GetProcessById(PID).MainWindowHandle, Integer)
        'ShowWindow(hWnd, SW_MAX)
        'ShowWindow(hWnd, ShowWindowCommands.ShowNoActivate)
        SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE Or SWP_NOSIZE)
  End Sub