问题描述
我从某个站点复制了此PowerShell代码,该代码显示了鼠标的当前位置:
I copied this PowerShell code from some site, that show the current position of the mouse:
[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
我查看了以此方式赋值:
I reviewed the System.Windows.Forms.Control class documentation and discovered several properties that are "sisters" of MousePosition (like Bottom, Bounds, Left, Location, Right or Top), that contain measures about the "control" in pixels, so I tried to also report the Location property values this way:
[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
但是此代码不起作用:未报告任何错误,但是位置值不会显示:
However this code don't works: no error is reported, but the Location values don't appear:
MousePosition: 368 431
Location:
为什么可以正确访问MousePosition属性,但不能正确访问 Location属性?
Why the MousePosition property can be correctly accessed, but the Location one not?
此代码的目的是获取运行PowerShell脚本的cmd.exe窗口的尺寸和位置(以像素为单位)。在PowerShell中获取这些值的正确方法是什么?
The purpose of this code is to get the dimensions and position in pixels of the cmd.exe window in which the PowerShell script run. What is the right way to get these values in PowerShell?
推荐答案
如果是,请输入 System.Windows.Forms。控件
不是您想要的-控制台主机不是Windows Forms控件。
If so, System.Windows.Forms.Control
is not what you want - the console host is not a Windows Forms control.
您可以从Win32 API中获取这些值( user32.dll
)和:
You can get these values from the Win32 API (user32.dll
) with the GetWindowRect
function:
$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
变量现在具有窗口的位置坐标:
The $WindowRect
variable now has the location coordinates of the Window:
PS C:\> $WindowRect.Top
45
这篇关于为什么可以读取System.Windows.Forms.Control MousePosition属性,但不能读取Location?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!