您的位置:首页 > 编程语言 > VB

章鱼哥出品——VB.NET 屏幕自适应功能的实现

2014-10-13 20:02 411 查看
最近有个网友问我屏幕自适应的问题,即如果屏幕的分辨率改变了,窗体也能适应屏幕的大小,不至于有些控件不能显示。其实代码还是很简单的,我不喜欢讲很多的原理啊什么的,直接上代码。所有代码可直接复制测试。方便后来人参考吧

<pre name="code" class="vb">'**********************************************
'作者:章鱼哥,QQ:3107073263 群:309816713    
'如有疑问或好的建议请联系我,大家一起进步    
'**********************************************

Imports System.Windows.Forms
Public Class Form1
    Dim Ini_Screen_Width As Integer = 1366 '开发时屏幕宽度
    Dim Ini_Screen_Height As Integer = 768 '开发时屏幕高度
    Dim Scale_X As Double '屏幕缩放比例
    Dim scale_Y As Double '屏幕缩放比例

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
       
        Dim Screen_Width As Integer = Screen.PrimaryScreen.Bounds.Width '当前屏幕的宽
        Dim Screen_Height As Integer = Screen.PrimaryScreen.Bounds.Height '当前屏幕的高

        '计算当前屏幕与开发时的屏幕的缩放比例
        Scale_X = Screen_Width / Ini_Screen_Width
        scale_Y = Screen_Height / Ini_Screen_Height

        '  MsgBox(Screen_Width & "*" & Screen_Height)
        '如果缩放比例为1,则不进行下面的操作
        If Scale_X = 1 And scale_Y = 1 Then
            Exit Sub
        End If

        '更新控件的大小
        Resize_Control()
    End Sub
  
    Private Sub Resize_Control()
        Me.Width = Me.Width * Scale_X
        Me.Height = Me.Height * scale_Y

        For Each cont As Control In Me.Controls
            UpdateControl(cont)
        Next
    End Sub
    Private Sub UpdateControl(ByVal Contr As Control)
        If Contr.Controls.Count > 0 Then
            For Each con As Control In Contr.Controls
                UpdateControl(con)
                With con
                    .Width *= Scale_X '宽度
                    .Height *= scale_Y '高度
                    .Location = New Point(.Location.X * Scale_X, .Location.Y * scale_Y) '更新位置
                    .Font = New Font(.Font.Name, .Font.Size * (Scale_X + scale_Y) / 2) '更新字体

                End With
            Next
        End If

    End Sub
End Class



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: