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)