You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows Form缩放适配问题:不同屏幕比例下尺寸异常

解决Windows Form高DPI缩放下的尺寸调整问题

问题根源

你直接用像素单位设置窗体宽度,但Windows在高DPI(125%/150%)模式下会自动对窗体进行缩放,导致代码设定的像素值被系统按缩放比例转换,实际显示尺寸和预期不符;极端情况下窗体被强制调整后,会出现标题栏按钮消失的问题。另外你代码里有语法错误:If me.width = 1026 = true then 多了冗余的= true,会导致逻辑判断出错。

具体解决步骤

  1. 修正代码语法错误
    把判断语句里多余的= true去掉,正确写法:

    If txt.TextLength = 4 Then
        If Me.Width = 1026 Then
            Me.Width = 1389
        ElseIf Me.Width = 1389 Then
            Me.Width = 1026
        End If
    End If
    
  2. 启用窗体高DPI感知
    让程序识别当前屏幕DPI缩放比例,避免系统强制缩放窗体。可以通过两种方式实现:

    • 方法一:修改app.manifest
      在项目的app.manifest文件中添加以下配置(如果没有这个文件,右键项目→添加→新建项→选择“应用程序清单文件”):
      <application xmlns="urn:schemas-microsoft-com:asm.v3">
        <windowsSettings>
          <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/PM</dpiAware>
        </windowsSettings>
      </application>
      
    • 方法二:通过代码设置DPI感知
      在VB的MyApplication类中添加以下代码(右键项目→属性→应用程序→查看应用程序事件):
      Protected Overrides Sub OnStartup(e As StartupEventArgs)
          MyBase.OnStartup(e)
          SetProcessDpiAwareness(PROCESS_DPI_AWARENESS.PROCESS_PER_MONITOR_DPI_AWARE)
      End Sub
      
      Private Enum PROCESS_DPI_AWARENESS
          PROCESS_DPI_UNAWARE = 0
          PROCESS_SYSTEM_DPI_AWARE = 1
          PROCESS_PER_MONITOR_DPI_AWARE = 2
      End Enum
      
      <System.Runtime.InteropServices.DllImport("user32.dll")>
      Private Shared Function SetProcessDpiAwareness(value As PROCESS_DPI_AWARENESS) As Boolean
      End Function
      
  3. 基于DPI比例计算实际像素宽度
    先获取当前屏幕的DPI缩放比例,再将目标逻辑宽度(100% DPI下的宽度)转换为实际像素宽度:

    If txt.TextLength = 4 Then
        ' 获取当前DPI缩放比例(96是100% DPI的基准值)
        Dim dpiScale As Single = Me.CreateGraphics().DpiX / 96.0F
        ' 100% DPI下的目标宽度
        Dim targetWidth1 As Integer = 1026
        Dim targetWidth2 As Integer = 1389
        ' 转换为对应DPI下的实际像素宽度
        Dim actualWidth1 As Integer = CInt(targetWidth1 * dpiScale)
        Dim actualWidth2 As Integer = CInt(targetWidth2 * dpiScale)
    
        If Me.Width = actualWidth1 Then
            Me.Width = actualWidth2
        ElseIf Me.Width = actualWidth2 Then
            Me.Width = actualWidth1
        End If
    End If
    

内容的提问来源于stack exchange,提问作者XNA_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 08:55:37