2016-04-16 20 views
3

我複製從一些網站上的這個PowerShell代碼,即顯示鼠標的當前位置:爲什麼可以讀取System.Windows.Forms.Control MousePosition屬性,但是位置不是?

[Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms') | Out-Null 
$control = [System.Windows.Forms.Control] 
$mouseX = $control::MousePosition.X 
$mouseY = $control::MousePosition.Y 
Write-Host 'MousePosition:' $mouseX $mouseY 

我回顧了System.Windows.Forms.Control class documentation,發現了幾個屬性,是MousePosition的「姐妹」(如底部,邊界,左,位置,右或頂部),包含關於像素「控制」措施,所以我試圖同時報告Location property值是這樣的:

[Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms') | Out-Null 
$control = [System.Windows.Forms.Control] 
$mouseX = $control::MousePosition.X 
$mouseY = $control::MousePosition.Y 
Write-Host 'MousePosition:' $mouseX $mouseY 
$locationX = $control::Location.X 
$locationY = $control::Location.Y 
Write-Host 'Location:' $locationX $locationY 

但是這個代碼不工作:沒有錯誤報告,但不顯示位置值:

MousePosition: 368 431 
Location: 

爲什麼MousePosition屬性可以正確訪問,但位置不是?

此代碼的目的是獲取運行PowerShell腳本的cmd.exe窗口的像素尺寸和位置。在PowerShell中獲取這些值的正確方法是什麼

+3

'MousePosition'是靜態的,'Location'不是(因爲它是每個控件的實例)。你必須從窗口句柄實例化一個'Control'對象,如果你想要它的位置 –

回答

2

此代碼的目的是獲取運行PowerShell腳本的cmd.exe窗口的像素尺寸和位置。在PowerShell中獲取這些值的正確方法是什麼?

如果是這樣,System.Windows.Forms.Control不是你想要的 - 控制檯主機不是Windows窗體控件。

您可以用GetWindowRect function獲得從Win32 API(user32.dll)這些值:

$WindowFunction,$RectangleStruct = Add-Type -MemberDefinition @' 
[DllImport("user32.dll", SetLastError = true)] 
[return: MarshalAs(UnmanagedType.Bool)] 
public static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect); 
[StructLayout(LayoutKind.Sequential)] 
public struct RECT 
{ 
    public int Left; 
    public int Top; 
    public int Right; 
    public int Bottom; 
} 
'@ -Name "type$([guid]::NewGuid() -replace '-')" -PassThru 

$MyWindowHandle = Get-Process -Id $PID |Select -ExpandProperty MainWindowHandle 
$WindowRect = New-Object -TypeName $RectangleStruct.FullName 
$null = $WindowFunction::GetWindowRect($MyWindowHandle,[ref]$WindowRect) 

$WindowRect變量現在有窗口的位置座標:

PS C:\> $WindowRect.Top 
45 
+0

非常感謝你的及時回答!我將你的代碼複製粘貼到'test.ps1'文件中,並且剛剛添加了'Write-Host'Left,Top,Right,Bottom:'$ WindowRect.Left $ WindowRect.Top $ WindowRect.Right $ WindowRect.Bottom' 。我使用這個命令從命令行執行它:'powershell Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope Process; \ test.ps1';輸出爲:'Left,Top,Right,Bottom:0 0 0 0' – Aacini

+0

在這種情況下,您需要獲取* parent *進程的MainWindowHandle(即cmd.exe進程),而不是當前正在運行的PowerShell實例 –

+0

Err ....我該怎麼做?對不起,PS新手在這裏... – Aacini

相關問題