为什么可以读取System.Windows.Forms.Control MousePosition属性,但位置不是?

时间:2016-04-16 16:04:46

标签: .net winforms powershell

我从某个站点复制了这个PowerShell代码,它显示了鼠标的当前位置:

[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“姐妹”的属性(如Bottom,Bounds,Left,Location,Right或Top),其中包含有关“控件”的度量,以像素为单位,所以我试图以这种方式报告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 中获取这些值的正确方法是什么?

1 个答案:

答案 0 :(得分: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变量现在具有Window的位置坐标:

PS C:\> $WindowRect.Top
45