Set shell = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")

' ===== CONFIG =====
exePath = "C:\PLM\Winprog\MobileInventory.exe"
workingDir = "C:\PLM\mgr1"
tempPS1 = "C:\PLM\Winprog\temp_minimize.ps1"

' ===== CHECK IF ALREADY RUNNING =====
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colProcesses = objWMIService.ExecQuery("Select * from Win32_Process Where Name = 'MobileInventory.exe'")

If colProcesses.Count > 0 Then
    ' App already running — exit silently
    WScript.Quit
End If

' ===== VALIDATE PATHS =====
If Not fso.FileExists(exePath) Then
    WScript.Quit
End If
If Not fso.FolderExists(workingDir) Then
    WScript.Quit
End If

' ===== SET WORKING DIRECTORY =====
shell.CurrentDirectory = workingDir

' ===== LAUNCH THE EXE =====
shell.Run Chr(34) & exePath & Chr(34), 1, False

' ===== WAIT BEFORE MINIMIZING =====
WScript.Sleep 3000

' ===== CREATE TEMP POWERSHELL TO MINIMIZE APP =====
Set tempFile = fso.CreateTextFile(tempPS1, True)
tempFile.WriteLine "Start-Sleep -Milliseconds 500"
tempFile.WriteLine "$proc = Get-Process MobileInventory -ErrorAction SilentlyContinue | Where-Object { $_.MainWindowHandle -ne 0 }"
tempFile.WriteLine "if ($proc) {"
tempFile.WriteLine "  $title = $proc.MainWindowTitle"
tempFile.WriteLine "  if ($title) {"
tempFile.WriteLine "    Add-Type -AssemblyName Microsoft.VisualBasic"
tempFile.WriteLine "    [Microsoft.VisualBasic.Interaction]::AppActivate($title)"
tempFile.WriteLine "    Start-Sleep -Milliseconds 300"
tempFile.WriteLine "    Add-Type -AssemblyName System.Windows.Forms"
tempFile.WriteLine "    [System.Windows.Forms.SendKeys]::SendWait('% {SPACE}')"
tempFile.WriteLine "    Start-Sleep -Milliseconds 200"
tempFile.WriteLine "    [System.Windows.Forms.SendKeys]::SendWait('n')"
tempFile.WriteLine "  }"
tempFile.WriteLine "}"
tempFile.Close

' ===== RUN IT SILENTLY AND CLEAN UP =====
shell.Run "powershell.exe -ExecutionPolicy Bypass -WindowStyle Hidden -File """ & tempPS1 & """", 0, True
If fso.FileExists(tempPS1) Then fso.DeleteFile tempPS1, True
