Restart Explorer Gracefully


Module Module1

    Public WM_USER = &H400

    Private Const WM_QUIT = &H12

    Private Declare Function PostMessage Lib "user32" _

   Alias "PostMessageA" _

  (ByVal hwnd As Long,

   ByVal wMsg As Long,

   ByVal wParam As Long,

   lParam As Long) As Long


    Private Declare Function RegisterWindowMessage Lib "user32" Alias "RegisterWindowMessageA" (ByVal lpString As String) As IntPtr

    Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr


    Sub Main()

        'Extra Help when trying to Clear Mapped Drives

        funWriteWordinColor("net use * /delete /y" & vbCrLf, ConsoleColor.Yellow)

        Process.Start("net.exe", "USE * /delete /Y").WaitForExit()


        Dim iWnd As Long = FindWindow("Shell_TrayWnd", Nothing)

        Console.WriteLine(iWnd)

        PostMessage(iWnd, WM_QUIT, 0, 0)

        Threading.Thread.Sleep(750)

        ''PostMessage(iWnd, WM_USER + 436, 0, 0)

        Process.Start("C:\Windows\System32\taskkill.exe", " /F /IM explorer.exe").WaitForExit()

        'Console.WriteLine("ENTER to launch Explorer")

        'Console.ReadLine()

        'Process.Start("c:\windows\explorer.exe")

        Dim StartProcess As New Process

        Dim StartInfo As New ProcessStartInfo

        StartInfo.FileName = "c:\windows\explorer.exe"

        StartInfo.UseShellExecute = True

        StartProcess.Start(StartInfo) '.WaitForExit()

        'StartProcess.WaitForExit()

        Console.WriteLine(".DELAY.")

        Threading.Thread.Sleep(3000)

    End Sub

End Module


Create SecureString

'https://codesnippets.fesslersoft.de/how-to-convert-a-string-to-securestring-using-c-and-vb-net/

Public Shared Function ToSecureString(source As String) As SecureString

    If String.IsNullOrWhiteSpace(source) Then

         Return Nothing

    End If

    Dim result = New SecureString()

    For Each c As char In source

      result.AppendChar(c)

    Next

    Return result

End Function