Author Posts

January 1, 2012 at 12:00 am

by clovisc at 2012-12-10 07:07:55

Hi,

I'm trying to do something similar to Autohotkey's IfwinExist, which means I'm trying to run an action whenever a window of a certain type is opened.

I don't really know how to go about it.

I tried creating an array that contains all open windows of the type I want, then waiting one second, then creating a second array with the same, then comparing the arrays.

It doesn't seem to work great.

Here's what I did:

Function check-newincs(){
#get all inc windows
$newwin1 = @((Select-Window -Title "INC* - Windows Internet *") | ? {$_.Processname -eq "iexplore"})
#count windows
$count = $newwin.Count
sleep 5
#get them again
$newwin = @((Select-Window -Title "INC* - Windows Internet *") | ? {$_.Processname -eq "iexplore"})
#if count gets bigger, then
if ((Arearraysequal $newwin $newwin1) -eq $false){
$a = (Compare-Object $newwin $newwin1)
Set-Variable newinc ($a.InputObject) -Scope global
activate-inc
}
sleep 1
}
Function do-checknewincs() {
While ($true) {
check-newincs
}
}

arearraysequal contains a function I found on internet, but I don't understand all subtleties of it because it isn't commented.

For example I do not know what ".rank" is, or what ".getEnumerator()" does. That I can obviuosly find on internet.

I will post arearraysequal here if you are interested:

function AreArraysEqual($a1, $a2) {
if ($a1 -isnot [array] -or $a2 -isnot [array]) {
throw "Both inputs must be an array"
}
if ($a1.Rank -ne $a2.Rank) {
return $false
}
if ([System.Object]::ReferenceEquals($a1, $a2)) {
return $true
}
for ($r = 0; $r -lt $a1.Rank; $r++) {
if ($a1.GetLength($r) -ne $a2.GetLength($r)) {
return $false
}
}
$enum1 = $a1.GetEnumerator()
$enum2 = $a2.GetEnumerator()
while ($enum1.MoveNext() -and $enum2.MoveNext()) {
if ($enum1.Current -ne $enum2.Current) {
return $false
}
}
return $true
}

Activate-inc just displays a message box with the title of the new window for now.

I use select-window from WASP, but I coul dalso have used the com object Shell.application and enumerated windows.

Thanks for any help on how to do this.

Clovis

by coderaven at 2012-12-17 12:04:59

Instead of doing all that, you may try looking at Get-Process and the MainWindowTitle property.
Get-Process | Select MainWindowTitle
This will list you all the window titles for the applications that have one. If you use
Get-Process | Where-Object {$_.MainWindowTitle -like *Some Title*}
in you loop you should get to where you want to go.