How to close the personalization window after spec

2019-09-07 03:04发布

I have some vbs code that will automatically change my windows theme via cmd as well as close it after the operation completes. The personalization window opens, Windows changes the theme, and then the personalization window closes. The problem is, sometimes the window doesn't close after changing the theme and I'm wondering why. Also, is there a one-liner code in cmd (or vbs that can execute through cmd) that just closes the personalization window? Thanks in advance for your help! My code used is as follows:

Set WshShell = WScript.CreateObject("WScript.Shell")

WshShell.Run "rundll32.exe %SystemRoot%\system32\shell32.dll,Control_RunDLL %SystemRoot%\system32\desk.cpl desk,@Themes /Action:OpenTheme /file:""C:\Windows\Resources\Ease of Access Themes\basic.theme"""

Wscript.Sleep 1600
WshShell.AppActivate("Desktop Properties")
WshShell.Sendkeys "%FC"
WshShell.Sendkeys "{F4}"

标签: vbscript cmd
2条回答
做个烂人
2楼-- · 2019-09-07 03:21

After trying a similar solution, I came up with the following powershell:

Function Get-WindowHandle($title,$class="") {
   $code = @'
      [System.Runtime.InteropServices.DllImport("User32.dll")]
      public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
'@
   Add-Type -MemberDefinition $code -Namespace MyWinAPI -Name GetWindowHandle
   return [MyWinAPI.GetWindowHandle]::FindWindow($class, $title)
}

Function Close-WindowHandle($windowHandle) {
   $code = @'
      [System.Runtime.InteropServices.DllImport("User32.dll")]
      public static extern bool PostMessage(IntPtr hWnd, int flags, int idk, int idk2);
'@
   Add-Type -MemberDefinition $code -Namespace MyWinAPI -Name CloseWindowHandle
   #https://msdn.microsoft.com/en-us/library/windows/desktop/ms632617(v=vs.85).aspx
   $WM_CLOSE = 0x0010
   return [MyWinAPI.CloseWindowHandle]::PostMessage($windowHandle, $WM_CLOSE, 0, 0)
}

Close-WindowHandle $(Get-WindowHandle 'Personalization' 'CabinetWClass')
查看更多
放荡不羁爱自由
3楼-- · 2019-09-07 03:32

Your Run call is being done asynchonously so your script will continue without waiting for Run to complete. This is fine, and it's what you need in your situation. But if it takes longer than 1600ms to launch the Desktop Properties dialog then AppActivate and your SendKeys commands are being sent to a nonexistent window. Have you tried increasing the sleep time to see if it works?

You can also test the availability of the window in a loop. AppActivate returns True if the window is found and False otherwise. For example, here's a snippet that tries for 10 seconds to see if the window appears (checking each second)...

For i = 1 To 10

    WScript.Sleep 1000

    If WshShell.AppActivate("Desktop Properties") Then
        WshShell.Sendkeys "%FC"
        WshShell.Sendkeys "{F4}"
        Exit For
    End If

Next

' If i > 10, it failed to find the window.
查看更多
登录 后发表回答