Home > database >  Powershell - Get current Active Window title and set it as a string
Powershell - Get current Active Window title and set it as a string

Time:12-15

I want to get my Active window's processName and MainWindowTitle then set it as a string Variable so that I can use it for later use, such in Filenaming.

My code does work but
(1) It can't display the $screenTitle
(2) There are some instances that MainWindowTitle is empty, but won't proceed to the If Condition even though I removed the $processNaming.

What have I missed here?

$code = @'
    [DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
   public static extern IntPtr GetForegroundWindow();
    [DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
       public static extern Int32 GetWindowThreadProcessId(IntPtr hWnd,out
Int32 lpdwProcessId);
'@

Add-Type $code -Name Utils -Namespace Win32
$myPid = [IntPtr]::Zero;

Do{

$hwnd = [Win32.Utils]::GetForegroundWindow()
$null = [Win32.Utils]::GetWindowThreadProcessId($hwnd, [ref] $myPid)

$processNaming = Get-Process | Where-Object ID -eq $myPid | Select-Object processName
#$processNaming
$screenTitle = Get-Process | Where-Object ID -eq $myPid | Select-Object MainWindowTitle

If($screenTitle -ne $Null){
    $processNaming
    $screenTitle
}
Else {
    Write-Host "No Screen Title"
}

Start-Sleep -Milliseconds 3000

}While($True)

CodePudding user response:

The issue with your code where $screenTitle is not being displayed happens because of how PowerShell displays objects in the console, currently you're trying to output 2 objects having different properties ProcessName and MainWindowTitle but only one is being displayed (the first one). See these answers for context on why these happens:

To overcome this, what you should do instead is return a single object with 2 properties this way you should see them correctly displayed.

$myPid = [IntPtr]::Zero;

Do {
    $hwnd = [Win32.Utils]::GetForegroundWindow()
    $null = [Win32.Utils]::GetWindowThreadProcessId($hwnd, [ref] $myPid)

    $process = Get-Process -Id $myPid

    If($process.MainWindowTitle) {
        $process | Select-Object ProcessName, MainWindowTitle
    }
    else {
        Write-Host ("No Screen Title for '{0}'" -f $process.ProcessName)
    }

    Start-Sleep -Seconds 1
} While($True)

If you want to output strings instead of an object from your loop you could do something like:

'ProcessName: {0} - MainWindowTitle: {1}' -f $process.ProcessName, $process.MainWindowTitle
  • Related