Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell - SetForegroundWindow

With a powershell code I try to change the position of a window (is works correctly) and put this windows "Always on top".

Please find below my code:

Import-Module C:/install/WASP/wasp.dll

for($i=1; $i -le 300000; $i++)
{
    $allWindow = Select-Window MyCheck*
    if($allWindow)
    {
        foreach ($currentWindow in $allWindow) 
        {
            $positionWindow = WindowPosition $currentWindow
            foreach ($currentPosition in $positionWindow) 
            {
                #if we find the correct windows
                if ( $currentWindow.title -match "\([0-9]*\)#" )
                {
                    #write-host "@@##@@"$currentWindow.title",(@@#@@)"$currentPosition.x",(@@#@@)"$currentPosition.y",(@@#@@)"$currentPosition.width",(@@#@@)"$currentPosition.height",(@@#@@)"$currentWindow.title",(@@#@@)"$currentWindow.IsActive

                    $id = $currentWindow.title.Substring($currentWindow.title.IndexOf("(")+1, $currentWindow.title.IndexOf(")")-$currentWindow.title.IndexOf("(")-1)
                    $allHUDWindow = Select-Window * | where {$_.Title -match "\($id\).*.txt"}
                    #If we find the second window, we have to superimpose $currentHUDWindow to $currentWindow
                    if($allHUDWindow)
                    {
                        foreach ($currentHUDWindow in $allHUDWindow) 
                        {

                            #I need to set $currentHUDWindow "Always on top"
                            Set-WindowActive $currentHUDWindow
                            Set-WindowPosition -X ($currentPosition.x-10) -Y ($currentPosition.y-30) -WIDTH ($currentPosition.width+20) -HEIGHT ($currentPosition.height+30) -Window $currentHUDWindow
                        }
                    }
                }
            }
        }
    }
} 

Currenlty, I call "Set-WindowActive $currentHUDWindow" but I need to apply also this kind of function :

 [DllImport("user32.dll")]
 [return: MarshalAs(UnmanagedType.Bool)]
 public static extern bool SetForegroundWindow(IntPtr hWnd);

I try to added this function to my code and called SetForegroundWindow($currentHUDWindow). But I encountered an error.

Could you please help me ?

I need to put the window $currentHUDWindow on top !

Thanks

like image 360
eldondano Avatar asked Oct 09 '12 13:10

eldondano


1 Answers

This is how P/invoke and use SetForegroundWindow

Add-Type @"
  using System;
  using System.Runtime.InteropServices;
  public class SFW {
     [DllImport("user32.dll")]
     [return: MarshalAs(UnmanagedType.Bool)]
     public static extern bool SetForegroundWindow(IntPtr hWnd);
  }
"@


$h =  (get-process NOTEPAD).MainWindowHandle # just one notepad must be opened!
[SFW]::SetForegroundWindow($h)
like image 156
CB. Avatar answered Nov 12 '22 16:11

CB.