none
How to regain focus on application RRS feed

  • Question

  • I have following code for PowerShell:

    $wshell = New-Object -ComObject WScript.Shell;
    $code = @'
        [DllImport("user32.dll")]
         public static extern IntPtr GetForegroundWindow();
    '@
    Add-Type $code -Name Utils -Namespace Win32
    while (1 -eq 1) {
        Sleep 50; # Interval (in seconds) between switch 
        $wshell.AppActivate('Opera');
        $wshell.SendKeys('^{PGUP}'); # Ctrl + Page Up keyboard shortcut to switch tab
        $wshell.SendKeys('{F5}'); # F5 to refresh active page
        Start-Sleep -Milliseconds 100
        $wshell.AppActivate('chrome');
    }

    It is supposed to refresh and cycle Opera tabs every 50 sec and then regain focus on open app (where I was working). It is working nicely but I have it static for Chrome and I need to load open app and after refresh regain focus to open app.


    • Edited by blacksool Friday, July 19, 2019 12:13 PM
    Friday, July 19, 2019 12:13 PM

Answers

  • https://gallery.technet.microsoft.com/scriptcenter/Get-Active-Window-on-User-352fa957

    Try this.

    $wshell = New-Object -ComObject WScript.Shell;
    Add-Type @"
      using System;
      using System.Runtime.InteropServices;
      public class Win32 {
        [DllImport("user32.dll")]
        public static extern IntPtr GetForegroundWindow();
    }
    "@
    while (1 -eq 1) {
        Sleep 50; # Interval (in seconds) between switch 
        $activeHandle = [Win32]::GetForegroundWindow()
        $Process = Get-Process | ? {$_.MainWindowHandle -eq $activeHandle} 
        $wshell.AppActivate('Opera');
        $wshell.SendKeys('^{PGUP}'); # Ctrl + Page Up keyboard shortcut to switch tab
        $wshell.SendKeys('{F5}'); # F5 to refresh active page
        Start-Sleep -Milliseconds 100
        $wshell.AppActivate($process.MainWindowTitle)
    }

    Friday, July 19, 2019 2:00 PM