Search code examples
windowspowershellinternet-explorerfocuscom-automation

Powershell New-Object -comobject InternetExplorer.Application bring to front


I searched but didn't find anything that specifically addresses this question.

Consider the code, can the new IE window be created in front of all other open windows? VBScript had the Run Method (Windows Script Host) that offered intWindowStyle Optional. Integer value indicating the appearance of the program's window. Note that not all programs make use of this information.

Does Powershell's new com object have anything similar?

Param(
[Parameter(Mandatory=$false)]
[string]$svr,
[Parameter(Mandatory=$false)]
[string]$last,
[Parameter(Mandatory=$false)]
[string]$desc,
[Parameter(Mandatory=$false)]
[string]$date)
$ie = new-object -comobject InternetExplorer.Application
$ie.navigate("http://www.stackoverflow.com")
# Wait for the page to finish loading
 do {sleep 1} until (-not ($ie.Busy))
$doc = $ie.document
$link = $doc.getElementById("Sym_Msg").Value = "$svr"
$link = $doc.getElementById("Lname").Value = "$last"
$link = $doc.getElementById("Desc").Value = "$desc"
$link = $doc.getElementById("Date_Ent").Value = "$date"
$button = $doc.getElementById("submit1")
$ie.Visible = $true
$button.click();
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($ie) | Out-Null

Solution

  • Unfortunately I don’t think this is part of ‘new-object’. There are several PowerShell extensions that implement this as cmdlet (Such as http://pscx.codeplex.com/ "Set-ForegroundWindow").

    The way this is implemented is a call to "user32.dll".

    In your code this should work:

    #Load DLL
    $pinvoke = '[DllImport("user32.dll")] public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow)'   
    Add-Type -MemberDefinition $pinvoke -name NativeMethods -namespace Win32
    
    #Get WindowHandle of the COM Object
    $hwnd = $ie.HWND
    
    # Minimize window
    [Win32.NativeMethods]::ShowWindowAsync($hwnd, 2)
    
    # Restore window
    [Win32.NativeMethods]::ShowWindowAsync($hwnd, 4)
    

    --Edited to add ' after nCmdShow)