我从某个网站复制了这个 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 类文档并发现了 MousePosition 的几个“姐妹”属性(如 Bottom、Bounds、Left、Location、Right 或 Top),其中包含有关“控件”(以像素为单位)的度量,因此我也尝试报告位置属性值是这样的:
[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属性可以正确访问,而Location属性却不能正确访问?
此代码的目的是获取运行 PowerShell 脚本的 cmd.exe 窗口的尺寸和位置(以像素为单位)。获取这些值的正确方法是什么在 PowerShell 中?
此代码的目的是获取运行 PowerShell 脚本的 cmd.exe 窗口的尺寸和位置(以像素为单位)。在 PowerShell 中获取这些值的正确方法是什么?
If so, System.Windows.Forms.Control
不是您想要的 - 控制台主机不是 Windows 窗体控件。
您可以从 Win32 API 获取这些值(user32.dll
)与GetWindowRect功能:
$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)
The $WindowRect
变量现在具有窗口的位置坐标:
PS C:\> $WindowRect.Top
45
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)