winforms PowerShell - DPI感知表单[副本]

2ekbmq32  于 2023-01-26  发布在  Shell
关注(0)|答案(2)|浏览(152)

此问题在此处已有答案

Why does powershell console incorrectly size my GUI form?(1个答案)
昨天关门了。
大家好,我很好奇在PowerShell中创建winform DPI时,如何才能让它知道?或者至少,阻止它自动缩放。我在谷歌上搜索了又搜索,但我似乎就是找不到答案或如何做到这一点的例子。最常见的答案是将其包含在清单中,但这对PowerShell来说不是一个可行的选择。
如果有什么我只是想防止Windows自动重新缩放我的形式在DPI高于96(100%)。我尝试了AutoScaleMode =“DPI”,不幸的是,这不工作,似乎没有做任何事情,因为设置为“无”或不包括它是相同的结果。
举个简单的例子...

Add-Type -AssemblyName 'System.Windows.Forms'
Add-Type -AssemblyName 'System.Drawing'

$Dialog = New-Object Windows.Forms.Form
$Dialog.Text = 'Main'
$Dialog.Size = New-Object Drawing.Size(200, 100)
$Dialog.AutoScaleMode = "DPI"

$Label = New-Object Windows.Forms.Label
$Label.Size = New-Object Drawing.Size(200, 16)
$Label.Location = New-Object Drawing.Size(10, 20)
$Label.Text = 'This text is to test autoscaling.'
$Dialog.Controls.Add($Label)

$Dialog.ShowDialog()

左边的图像是自动缩放的,而且很模糊。我不想这样,我想让它看起来像右边。如果我能做到这一点,我会试着弄清楚我将如何处理缩放。

m1m5dgzv

m1m5dgzv1#

所以我偶然找到了一个解决方法。我正在研究WPF表单(我对它知之甚少),偶然发现了一个例子。在WPF中添加一个最小的虚拟窗口,实际上从来没有显示过,不知何故阻止了winform自动缩放。

# Load assemblies.
Add-Type -AssemblyName 'System.Windows.Forms'
Add-Type -AssemblyName 'System.Drawing'
Add-Type -AssemblyName 'PresentationFramework'

# Dummy WPF window (prevents auto scaling).
[xml]$Xaml = @"
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Name="Window">
</Window>
"@
$Reader = (New-Object System.Xml.XmlNodeReader $Xaml)
$Window = [Windows.Markup.XamlReader]::Load($Reader)

# Business as usual.
$Dialog = New-Object Windows.Forms.Form
$Dialog.Text = 'Main Window'
$Dialog.Size = New-Object Drawing.Size(200, 100)

$Label = New-Object Windows.Forms.Label
$Label.Size = New-Object Drawing.Size(200, 16)
$Label.Location = New-Object Drawing.Size(10, 20)
$Label.Text = 'This text is to test autoscaling.'
$Dialog.Controls.Add($Label)

$Dialog.ShowDialog()
axzmvihb

axzmvihb2#

老问题,但很有趣。而且不用虚拟WPF窗口也可以使表单DPI感知。下面的示例使用SetProcessDPIAware使表单DPI感知:

using assembly System.Windows.Forms
using namespace System.Windows.Forms
using namespace System.Drawing

#Enable visual styles
[Application]::EnableVisualStyles()

#Enable DPI awareness
$code = @"
    [System.Runtime.InteropServices.DllImport("user32.dll")]
    public static extern bool SetProcessDPIAware();
"@
$Win32Helpers = Add-Type -MemberDefinition $code -Name "Win32Helpers" -PassThru
$null = $Win32Helpers::SetProcessDPIAware()

$form = [Form] @{
    ClientSize = [Point]::new(300, 80);
    StartPosition = "CenterScreen";
    Text = "Test";
    AutoScaleDimensions = [SizeF]::new(6, 13);
    AutoScaleMode = [AutoScaleMode]::Font;
}
$label = [Label] @{
    Text = "Hello, world!";
    AutoSize = $true;
    Location = [Point]::new(8,8)
}
$form.Controls.Add($label)

$null = $form.ShowDialog()
$form.Dispose()

使用SetProcessDPIAware,您可以看到不同之处:

没有SetProcessDPIAware:

相关问题