Imports System.Runtime.InteropServices
Imports System.Text
Imports System.IO

Namespace Win32
    Public Delegate Function NativeCallbackHandler( _
        ByVal handle As IntPtr, _
        ByVal parameter As Integer) As Boolean

    Public Class NativeFunctions
        <DllImport("user32.dll")> _
        Public Shared Function GetForegroundWindow() As IntPtr
        End Function

        <DllImport("user32.dll")> _
        Public Shared Function RegisterHotKey( _
            ByVal hWnd As IntPtr, _
            ByVal id As Integer, _
            ByVal fsModifiers As Integer, _
            ByVal vk As Integer) As Boolean
        End Function

        <DllImport("user32.dll")> _
        Public Shared Function UnregisterHotKey( _
            ByVal hWnd As IntPtr, _
            ByVal id As Integer) As Boolean
        End Function

        <DllImport("user32.dll", CharSet:=CharSet.Auto)> _
        Public Shared Function SetWindowText( _
            ByVal hWnd As IntPtr, _
            ByVal lpString As String) As Boolean
        End Function

        <DllImport("shell32.dll", CharSet:=CharSet.Auto)> _
        Public Shared Function SHGetFileInfo( _
            ByVal pszPath As String, _
            ByVal dwFileAttributes As Integer, _
            ByRef psfi As SHFILEINFO, _
            ByVal cbSizeFileInfo As Integer, _
            ByVal uFlags As Integer) As IntPtr
        End Function

        <DllImport("kernel32.dll", CharSet:=CharSet.Auto)> _
        Public Shared Function GetVolumeInformation( _
            ByVal lpRootPathName As String, _
            ByVal lpVolumeNameBuffer As StringBuilder, _
            ByVal nVolumeNameSize As Integer, _
            ByRef lpVolumeSerialNumber As Integer, _
            ByRef lpMaximumComponentLength As Integer, _
            ByRef lpFileSystemFlags As Integer, _
            ByVal lpFileSystemNameBuffer As StringBuilder, _
            ByVal nFileSystemNameSize As Integer) As Boolean
        End Function

        <DllImport("kernel32.dll", CharSet:=CharSet.Auto)> _
        Public Shared Function GetDiskFreeSpaceEx( _
            ByVal lpDirectoryName As String, _
            ByRef lpFreeBytesAvailableToCaller As Long, _
            ByRef lpTotalNumberOfBytes As Long, _
            ByRef lpTotalNumberOfFreeBytes As Long) As Integer
        End Function

        <DllImport("kernel32.dll", CharSet:=CharSet.Auto)> _
        Public Shared Function GetDriveType(ByVal rootDir As String) As Integer
        End Function

        <DllImport("user32.dll", CharSet:=CharSet.Auto)> _
        Public Shared Function GetWindowText( _
            ByVal hWnd As IntPtr, _
            ByVal lpString As StringBuilder, _
            ByVal nMaxCount As Integer) As Integer
        End Function

        <DllImport("user32.dll")> _
        Public Shared Function ShowWindow( _
            ByVal handle As IntPtr, _
            ByVal nCmdShow As SW) As Integer
        End Function

        <DllImport("user32.dll")> _
        Public Shared Function EnumWindows( _
            ByVal ewp As NativeCallbackHandler, _
            ByVal ByVallParam As IntPtr) As Boolean
        End Function

        <DllImport("user32.dll")> _
        Public Shared Function EnumChildWindows( _
            ByVal hwndParent As IntPtr, _
            ByVal ByVallpEnumProc As NativeCallbackHandler, _
            ByVal parameter As IntPtr) As Boolean
        End Function

        'using same types as the Message class
        <DllImport("user32.dll", CharSet:=CharSet.Auto)> _
        Public Shared Function SendMessage( _
            ByVal handle As IntPtr, _
            ByVal message As Integer, _
            ByVal wParam As IntPtr, _
            ByVal lParam As IntPtr) As Integer
        End Function

        <DllImport("user32.dll", CharSet:=CharSet.Auto)> _
        Public Shared Function PostMessage( _
           ByVal hwnd As IntPtr, _
           ByVal wMsg As Integer, _
           ByVal wParam As IntPtr, _
           ByVal lParam As IntPtr) As Int32
        End Function

        <DllImport("wininet.dll")> _
        Public Shared Function InternetGetConnectedState( _
            ByRef description As Integer, _
            ByVal reservedValue As Integer) As Boolean
        End Function
    End Class

    Public Class Win32Window
        Private Shared WindowHandles As New ArrayList
        Private Shared ChildHandles As New ArrayList

        Public Shared Sub Show(ByVal handle As IntPtr)
            NativeFunctions.ShowWindow(handle, SW.RESTORE)
        End Sub

        Public Shared Sub Show(ByVal title As String)
            For Each handle As IntPtr In GetHandles()
                If GetTitle(handle).Contains(title) Then
                    NativeFunctions.ShowWindow(handle, SW.RESTORE)
                End If
            Next
        End Sub

        Public Shared Sub Hide(ByVal handle As IntPtr)
            NativeFunctions.ShowWindow(handle, SW.HIDE)
        End Sub

        Public Shared Sub Hide(ByVal title As String)
            For Each handle As IntPtr In GetHandles()
                If GetTitle(handle).Contains(title) Then
                    NativeFunctions.ShowWindow(handle, SW.HIDE)
                End If
            Next
        End Sub

        Public Shared Function GetHandles() As IntPtr()
            NativeFunctions.EnumWindows(AddressOf EnumWindowsProc, Nothing)
            Dim winHandles(WindowHandles.Count - 1) As IntPtr
            WindowHandles.CopyTo(winHandles)
            WindowHandles.Clear()
            Return winHandles
        End Function

        Private Shared Function EnumWindowsProc(ByVal handle As IntPtr, ByVal parameter As Integer) As Boolean
            WindowHandles.Add(handle)
            Return True
        End Function

        Public Shared Function GetTitle(ByVal handle As IntPtr) As String
            Dim sb As New StringBuilder(255)
            NativeFunctions.GetWindowText(handle, sb, sb.Capacity)
            Return sb.ToString
        End Function

        Private Shared Function GetChildHandles(ByVal handle As IntPtr) As IntPtr()
            NativeFunctions.EnumChildWindows(handle, AddressOf HandleChildCallback, Nothing)
            Dim cHandles(ChildHandles.Count - 1) As IntPtr
            ChildHandles.CopyTo(cHandles)
            ChildHandles.Clear()
            Return cHandles
        End Function

        Private Shared Function HandleChildCallback(ByVal handle As IntPtr, ByVal parameter As Integer) As Boolean
            ChildHandles.Add(handle)
            Return True
        End Function

        Public Shared Function GetChildText(ByVal handle As IntPtr) As String
            Dim ip As IntPtr = Marshal.AllocHGlobal(1000)
            NativeFunctions.SendMessage(handle, WM.GETTEXT, New IntPtr(1000), ip)
            Dim ret As String = Marshal.PtrToStringAuto(ip)
            Marshal.FreeHGlobal(ip)
            Return ret
        End Function

        Public Shared Function GetHandle(ByVal title As String) As IntPtr
            For Each handle As IntPtr In GetHandles()
                If GetTitle(handle).Contains(title) Then
                    Return handle
                End If
            Next
        End Function

        Public Shared Function Exists(ByVal title As String, ByVal text As String) As Boolean
            Dim handle, childhandle As IntPtr
            Dim currentTitle, currentChildTitle As String
            For Each handle In GetHandles()
                currentTitle = GetTitle(handle)
                If currentTitle <> "" AndAlso currentTitle.Contains(title) Then
                    For Each childhandle In GetChildHandles(handle)
                        currentChildTitle = GetChildText(childhandle)
                        If currentChildTitle <> "" AndAlso currentChildTitle.Contains(text) Then
                            Return True
                        End If
                    Next
                End If
            Next
        End Function

        Public Shared Sub Close(ByVal title As String)
            Dim handle As IntPtr
            Dim currentTitle As String

            For Each handle In GetHandles()
                currentTitle = GetTitle(handle)
                If currentTitle <> "" AndAlso currentTitle.Contains(title) Then
                    NativeFunctions.SendMessage(handle, WM.CLOSE, IntPtr.Zero, IntPtr.Zero)
                End If
            Next
        End Sub
    End Class

    Public Class Win32Help
        Public Shared Function GetHDWithMostFreeSpace() As String
            Dim space As Integer
            Dim driveValue As Integer
            Dim dir As String = "C:\"

            For Each i As String In Directory.GetLogicalDrives()
                If NativeFunctions.GetDriveType(i) = Drive.FIXED Then
                    driveValue = GetFreeSpaceMB(i)

                    If driveValue > space Then
                        space = driveValue
                        dir = i
                    End If
                End If
            Next

            Return dir
        End Function

        Public Shared Function GetFreeSpaceMB(ByVal rootDir As String) As Integer
            Dim freeBytes As Long
            NativeFunctions.GetDiskFreeSpaceEx(rootDir, freeBytes, Nothing, Nothing)
            Return CInt(freeBytes / 1024 / 1024)
        End Function

        Public Shared Function GetSmallIcon(ByVal path As String) As Icon
            Dim shinfo As New SHFILEINFO

            NativeFunctions.SHGetFileInfo(path, 0, shinfo, Marshal.SizeOf(shinfo), _
                SHGFI.ICON Or SHGFI.SMALLICON)

            Return Icon.FromHandle(shinfo.hIcon)
        End Function

        Public Shared Function GetLargeIcon(ByVal path As String) As Icon
            Dim shinfo As New SHFILEINFO

            NativeFunctions.SHGetFileInfo(path, 0, shinfo, Marshal.SizeOf(shinfo), _
                SHGFI.ICON Or SHGFI.LARGEICON)

            Return Icon.FromHandle(shinfo.hIcon)
        End Function

        Public Shared Function IsConnectedToInternet() As Boolean
            Dim Desc As Integer
            Return NativeFunctions.InternetGetConnectedState(Desc, 0)
        End Function

        Public Shared Function GetFreeSpaceGB(ByVal rootDir As String) As Integer
            Return CInt(GetFreeSpaceMB(rootDir) / 1024)
        End Function

        Public Shared Function GetVolumeName(ByVal rootDirectory As String) As String
            Dim volumeName As New StringBuilder(256)
            Dim fileSystemNameBuffer As New StringBuilder(256)

            NativeFunctions.GetVolumeInformation(rootDirectory, volumeName, _
                volumeName.Capacity, 0, 0, 0, fileSystemNameBuffer, _
                fileSystemNameBuffer.Capacity)

            Return volumeName.ToString
        End Function
    End Class

    Public Structure SHFILEINFO
        Public hIcon As IntPtr
        Public iIcon As Integer
        Public dwAttributes As Integer
        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=260)> _
        Public szDisplayName As String
        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=80)> _
        Public szTypeName As String
    End Structure

#Region " Enums "
    Public Enum WM
        ACTIVATE = &H6
        ACTIVATEAPP = &H1C
        AFXFIRST = &H360
        AFXLAST = &H37F
        APP = &H8000
        ASKCBFORMATNAME = &H30C
        CANCELJOURNAL = &H4B
        CANCELMODE = &H1F
        CAPTURECHANGED = &H215
        CHANGECBCHAIN = &H30D
        [CHAR] = &H102
        CHARTOITEM = &H2F
        CHILDACTIVATE = &H22
        CLEAR = &H303
        CLOSE = &H10
        COMMAND = &H111
        COMPACTING = &H41
        COMPAREITEM = &H39
        CONTEXTMENU = &H7B
        COPY = &H301
        COPYDATA = &H4A
        CREATE = &H1
        CTLCOLORBTN = &H135
        CTLCOLORDLG = &H136
        CTLCOLOREDIT = &H133
        CTLCOLORLISTBOX = &H134
        CTLCOLORMSGBOX = &H132
        CTLCOLORSCROLLBAR = &H137
        CTLCOLORSTATIC = &H138
        CUT = &H300
        DEADCHAR = &H103
        DELETEITEM = &H2D
        DESTROY = &H2
        DESTROYCLIPBOARD = &H307
        DEVICECHANGE = &H219
        DEVMODECHANGE = &H1B
        DISPLAYCHANGE = &H7E
        DRAWCLIPBOARD = &H308
        DRAWITEM = &H2B
        DROPFILES = &H233
        ENABLE = &HA
        ENDSESSION = &H16
        ENTERIDLE = &H121
        ENTERMENULOOP = &H211
        ENTERSIZEMOVE = &H231
        ERASEBKGND = &H14
        EXITMENULOOP = &H212
        EXITSIZEMOVE = &H232
        FONTCHANGE = &H1D
        GETDLGCODE = &H87
        GETFONT = &H31
        GETHOTKEY = &H33
        GETICON = &H7F
        GETMINMAXINFO = &H24
        GETOBJECT = &H3D
        GETTEXT = &HD
        GETTEXTLENGTH = &HE
        HANDHELDFIRST = &H358
        HANDHELDLAST = &H35F
        HELP = &H53
        HOTKEY = &H312
        HSCROLL = &H114
        HSCROLLCLIPBOARD = &H30E
        ICONERASEBKGND = &H27
        IME_CHAR = &H286
        IME_COMPOSITION = &H10F
        IME_COMPOSITIONFULL = &H284
        IME_CONTROL = &H283
        IME_ENDCOMPOSITION = &H10E
        IME_KEYDOWN = &H290
        IME_KEYLAST = &H10F
        IME_KEYUP = &H291
        IME_NOTIFY = &H282
        IME_REQUEST = &H288
        IME_SELECT = &H285
        IME_SETCONTEXT = &H281
        IME_STARTCOMPOSITION = &H10D
        INITDIALOG = &H110
        INITMENU = &H116
        INITMENUPOPUP = &H117
        INPUTLANGCHANGE = &H51
        INPUTLANGCHANGEREQUEST = &H50
        KEYDOWN = &H100
        KEYFIRST = &H100
        KEYLAST = &H108
        KEYUP = &H101
        KILLFOCUS = &H8
        LBUTTONDBLCLK = &H203
        LBUTTONDOWN = &H201
        LBUTTONUP = &H202
        MBUTTONDBLCLK = &H209
        MBUTTONDOWN = &H207
        MBUTTONUP = &H208
        MDIACTIVATE = &H222
        MDICASCADE = &H227
        MDICREATE = &H220
        MDIDESTROY = &H221
        MDIGETACTIVE = &H229
        MDIICONARRANGE = &H228
        MDIMAXIMIZE = &H225
        MDINEXT = &H224
        MDIREFRESHMENU = &H234
        MDIRESTORE = &H223
        MDISETMENU = &H230
        MDITILE = &H226
        MEASUREITEM = &H2C
        MENUCHAR = &H120
        MENUCOMMAND = &H126
        MENUDRAG = &H123
        MENUGETOBJECT = &H124
        MENURBUTTONUP = &H122
        MENUSELECT = &H11F
        MOUSEACTIVATE = &H21
        MOUSEFIRST = &H200
        MOUSEHOVER = &H2A1
        MOUSELAST = &H20A
        MOUSELEAVE = &H2A3
        MOUSEMOVE = &H200
        MOUSEWHEEL = &H20A
        MOVE = &H3
        MOVING = &H216
        NCACTIVATE = &H86
        NCCALCSIZE = &H83
        NCCREATE = &H81
        NCDESTROY = &H82
        NCHITTEST = &H84
        NCLBUTTONDBLCLK = &HA3
        NCLBUTTONDOWN = &HA1
        NCLBUTTONUP = &HA2
        NCMBUTTONDBLCLK = &HA9
        NCMBUTTONDOWN = &HA7
        NCMBUTTONUP = &HA8
        NCMOUSEMOVE = &HA0
        NCPAINT = &H85
        NCRBUTTONDBLCLK = &HA6
        NCRBUTTONDOWN = &HA4
        NCRBUTTONUP = &HA5
        NEXTDLGCTL = &H28
        NEXTMENU = &H213
        NOTIFY = &H4E
        NOTIFYFORMAT = &H55
        NULL = &H0
        PAINT = &HF
        PAINTCLIPBOARD = &H309
        PAINTICON = &H26
        PALETTECHANGED = &H311
        PALETTEISCHANGING = &H310
        PARENTNOTIFY = &H210
        PASTE = &H302
        PENWINFIRST = &H380
        PENWINLAST = &H38F
        POWER = &H48
        PRINT = &H317
        PRINTCLIENT = &H318
        QUERYDRAGICON = &H37
        QUERYENDSESSION = &H11
        QUERYNEWPALETTE = &H30F
        QUERYOPEN = &H13
        QUEUESYNC = &H23
        QUIT = &H12
        RBUTTONDBLCLK = &H206
        RBUTTONDOWN = &H204
        RBUTTONUP = &H205
        RENDERALLFORMATS = &H306
        RENDERFORMAT = &H305
        SETCURSOR = &H20
        SETFOCUS = &H7
        SETFONT = &H30
        SETHOTKEY = &H32
        SETICON = &H80
        SETREDRAW = &HB
        SETTEXT = &HC
        SETTINGCHANGE = &H1A
        SHOWWINDOW = &H18
        SIZE = &H5
        SIZECLIPBOARD = &H30B
        SIZING = &H214
        SPOOLERSTATUS = &H2A
        STYLECHANGED = &H7D
        STYLECHANGING = &H7C
        SYNCPAINT = &H88
        SYSCHAR = &H106
        SYSCOLORCHANGE = &H15
        SYSCOMMAND = &H112
        SYSDEADCHAR = &H107
        SYSKEYDOWN = &H104
        SYSKEYUP = &H105
        TCARD = &H52
        TIMECHANGE = &H1E
        TIMER = &H113
        UNDO = &H304
        UNINITMENUPOPUP = &H125
        USER = &H400
        USERCHANGED = &H54
        VKEYTOITEM = &H2E
        VSCROLL = &H115
        VSCROLLCLIPBOARD = &H30A
        WINDOWPOSCHANGED = &H47
        WINDOWPOSCHANGING = &H46
        WININICHANGE = &H1A
    End Enum

    Public Enum WS As UInteger
        ACTIVECAPTION = &H1
        BORDER = &H800000
        CAPTION = &HC00000
        CHILD = &H40000000
        CHILDWINDOW = CHILD
        CLIPCHILDREN = &H2000000
        CLIPSIBLINGS = &H4000000
        DISABLED = &H8000000
        DLGFRAME = &H400000
        EX_ACCEPTFILES = &H10I
        EX_APPWINDOW = &H40000I
        EX_CLIENTEDGE = &H200I
        EX_CONTEXTHELP = &H400I
        EX_CONTROLPARENT = &H10000I
        EX_DLGMODALFRAME = &H1I
        EX_LAYERED = &H80000
        EX_LAYOUTRTL = &H400000I
        EX_LEFT = &H0I
        EX_LEFTSCROLLBAR = &H4000I
        EX_LTRREADING = &H0I
        EX_MDICHILD = &H40I
        EX_NOACTIVATE = &H8000000I
        EX_NOINHERITLAYOUT = &H100000I
        EX_NOPARENTNOTIFY = &H4I
        EX_OVERLAPPEDWINDOW = (EX_WINDOWEDGE Or EX_CLIENTEDGE)
        EX_PALETTEWINDOW = (EX_WINDOWEDGE Or EX_TOOLWINDOW Or EX_TOPMOST)
        EX_RIGHT = &H1000I
        EX_RIGHTSCROLLBAR = &H0I
        EX_RTLREADING = &H2000I
        EX_STATICEDGE = &H20000I
        EX_TOOLWINDOW = &H80I
        EX_TOPMOST = &H8I
        EX_TRANSPARENT = &H20I
        EX_WINDOWEDGE = &H100I
        GROUP = &H20000
        GT = (GROUP Or TABSTOP)
        HSCROLL = &H100000
        ICONIC = MINIMIZE
        MAXIMIZE = &H1000000
        MAXIMIZEBOX = &H10000
        MINIMIZE = &H20000000
        MINIMIZEBOX = &H20000
        OVERLAPPED = &H0I
        OVERLAPPEDWINDOW = OVERLAPPED Or CAPTION Or SYSMENU Or THICKFRAME Or MINIMIZEBOX Or MAXIMIZEBOX
        'POPUP = &H80000000 'shouldn't this work?
        'POPUPWINDOW = (POPUP Or BORDER Or SYSMENU)
        SIZEBOX = THICKFRAME
        SYSMENU = &H80000
        TABSTOP = &H10000
        THICKFRAME = &H40000
        TILED = OVERLAPPED
        TILEDWINDOW = OVERLAPPEDWINDOW
        VISIBLE = &H10000000
        VSCROLL = &H200000
    End Enum

    Public Enum Drive
        CDROM = 5
        FIXED = 3
        NO_ROOT_DIR = 1
        RAMDISK = 6
        REMOTE = 4
        REMOVABLE = 2
        UNKNOWN = 0
    End Enum

    Public Enum SHGFI
        ICON = 256
        LARGEICON = 0
        SMALLICON = 1
    End Enum

    Public Enum SW
        HIDE = 0
        SHOWNA = 8
        RESTORE = 9
    End Enum

    Public Enum [Mod]
        CONTROL = 2
        ALT = 1
        WIN = 8
    End Enum

    Public Enum HT
        HTBORDER = 18
        HTBOTTOM = 15
        HTBOTTOMLEFT = 16
        HTBOTTOMRIGHT = 17
        HTCAPTION = 2
        HTCLIENT = 1
        HTCLOSE = 20
        HTERROR = -2
        HTGROWBOX = 4
        HTHELP = 21
        HTHSCROLL = 6
        HTLEFT = 10
        HTMAXBUTTON = 9
        HTMENU = 5
        HTMINBUTTON = 8
        HTNOWHERE = 0
        HTOBJECT = 19
        HTREDUCE = HTMINBUTTON
        HTRIGHT = 11
        HTSIZE = HTGROWBOX
        HTSIZEFIRST = HTLEFT
        HTSIZELAST = HTBOTTOMRIGHT
        HTSYSMENU = 3
        HTTOP = 12
        HTTOPLEFT = 13
        HTTOPRIGHT = 14
    End Enum

    Public Enum SC
        ARRANGE = &HF110
        CLOSE = &HF060I
        CONTEXTHELP = &HF180
        [DEFAULT] = &HF160
        DLG_FORCE_UI = &H4
        DLG_MINIMAL_UI = &H1
        DLG_NO_UI = &H2
        FLAGS = &H400
        HOTKEY = &HF150
        HSCROLL = &HF080
        ICON = MINIMIZE
        KEYMENU = &HF100
        MANAGER_CONNECT = &H1
        MANAGER_CREATE_SERVICE = &H2
        MANAGER_ENUMERATE_SERVICE = &H4
        MANAGER_LOCK = &H8
        MANAGER_MODIFY_BOOT_CONFIG = &H20
        MANAGER_QUERY_LOCK_STATUS = &H10
        MAXIMIZE = &HF030
        MINIMIZE = &HF020
        MONITORPOWER = &HF170
        MOUSEMENU = &HF090
        MOVE = &HF010
        NEXTWINDOW = &HF040
        PREVWINDOW = &HF050
        RESTORE = &HF120
        SCREENSAVE = &HF140
        SEPARATOR = &HF00F
        SIZE = &HF000
        TASKLIST = &HF130
        VSCROLL = &HF070
        ZOOM = MAXIMIZE
    End Enum
#End Region

End Namespace