简体   繁体   中英

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM