2015-01-08 65 views
0

我已經建立了一個PowerShell腳本(使用wasp),它將任意窗口設置爲「始終在頂部」模式。通過鼠標光標在Powershell/wasp中獲取窗口標題?

我通過運行該腳本:

Get-WindowByTitle *emul* | Set-TopMost

  • 爲什麼我需要它*

當我Eclipse/Androidstudio計劃 - 我想模擬器總是在前面?所以腳本正在尋找所有標題爲emul,它是實際標題的一部分,即"emulator.exe")的所有窗口,並將其始終置於最前。

好的。

但是現在我想在不改變腳本的情況下爲每個窗口執行此操作。

我將如何選擇窗口?通過鼠標光標(僅懸停)。 (當我把鼠標的calc.exe,然後按下鍵的一些序列 - 這將激活PS腳本 - 它會搜索哪個窗口光標在

問題

哪有我選擇了一個窗口上有鼠標光標的title? (窗口必須激活)

例子:

看:

enter image description here

我想MyChromeBrowserTitle雖然它是在後臺,(和記事本在前面)。它應該返回chrome的標題,因爲光標位於chrome窗口。

回答

2

以下可能不是這樣做的最佳方式,並且它不適用於資源管理器窗口,因爲資源管理器正在運行桌面+某些特定的文件夾資源管理器窗口。然而,它適用於其餘的。

Add-Type -TypeDefinition @" 
using System; 
using System.Runtime.InteropServices; 
public class Utils 
{ 
    public struct RECT 
    { 
     public int Left;   
     public int Top;   
     public int Right;  
     public int Bottom;  
    } 

    [DllImport("user32.dll")] 
    public static extern bool GetWindowRect(
     HandleRef hWnd, 
     out RECT lpRect); 
} 
"@ 

Add-Type -AssemblyName System.Windows.Forms 
$p = [Windows.Forms.Cursor]::Position 
Get-Process | %{ 
    if ($_.MainWindowHandle) 
    { 
     $o = New-Object -TypeName System.Object    
     $href = New-Object -TypeName System.RunTime.InteropServices.HandleRef -ArgumentList $o, $_.MainWindowHandle    

     $rect = New-Object utils+RECT    
     [Void][Utils]::GetWindowRect($href, [ref]$rect) 

     if ($p.X -ge $rect.Left -and $p.X -le $rect.Right -and 
      $p.Y -ge $rect.Top -and $p.Y -le $rect.Bottom 
      ) 
     { 
      $_.MainWindowTitle 
     } 
    } 
} 

編輯

正如我運行PowerShell的V3,上面的代碼爲我工作。

我試過設置Set-StrictMode -Version 2,所以我們運行的是相同的版本。 以下V2適合我:

$def = @' 
public struct RECT 
{ 
    public int Left; 
    public int Top; 
    public int Right; 
    public int Bottom; 
} 

[DllImport("user32.dll")] 
public static extern bool GetWindowRect(
    HandleRef hWnd, 
    out RECT lpRect); 

'@ 

Add-Type -MemberDefinition $def -Namespace Utils -Name Utils 

Add-Type -AssemblyName System.Windows.Forms 
$p = [Windows.Forms.Cursor]::Position 
Get-Process | %{ 
    if ($_.MainWindowHandle) 
    { 
     $o = New-Object -TypeName System.Object    
     $href = New-Object -TypeName System.RunTime.InteropServices.HandleRef -ArgumentList $o, $_.MainWindowHandle    

     $rect = New-Object Utils.Utils+RECT    
     [Void][Utils.Utils]::GetWindowRect($href, [ref]$rect) 

     if ($p.X -ge $rect.Left -and $p.X -le $rect.Right -and 
      $p.Y -ge $rect.Top -and $p.Y -le $rect.Bottom 
      ) 
     { 
      $_.MainWindowTitle 
     } 
    } 
} 
+0

謝謝,但爲什麼我會得到這些錯誤? http://i.imgur.com/rxdh7xO.png –

+0

的確很有意思,在ISE或其他Powershell編輯器中很有用。你正在使用哪個版本的Powershell? –

+0

http://i.imgur.com/xhbzuvT.png –