Как заблокировать форму от дальнейшего изменения размера с изменением соотношения сторон

В настоящее время я использую этот код, и он работает безупречно

Мой вопрос заключается в том, как мне изменить WndProc, чтобы он остановился на моем предпочтительном пределе ширины и высоты. Хорошо, я решил это, установив MinimumSize, но возникает новая проблема, когда соотношение сторон формы достигает ограничение размера рабочего стола Windows maximum right, он начинает искажать соотношение сторон, вместо того, чтобы блокироваться, начинает растягиваться.

Нужно как-то исправить WndProc с SystemInformation.VirtualScreen.Width, чтобы остановить увеличение обоих размеров при достижении предельной ширины.

Я добавил это, что работает, но это все еще только для моего разрешения, как мне сделать его универсальным для поддержки всех разрешений.

        If r.right - r.left > SystemInformation.VirtualScreen.Width Then
            r.bottom = 900 'quick fix (not good) how to calculate this value?
        End If

источник кода: http://www.vb-helper.com/howto_net_form_fixed_aspect.html

Imports System.Runtime.InteropServices
...
Public Structure Rect
    Public left As Integer
    Public top As Integer
    Public right As Integer
    Public bottom As Integer
End Structure

Protected Overrides Sub WndProc(ByRef m As _
    System.Windows.Forms.Message)
    Static first_time As Boolean = True
    Static aspect_ratio As Double
    Const WM_SIZING As Long = &H214
    Const WMSZ_LEFT As Integer = 1
    Const WMSZ_RIGHT As Integer = 2
    Const WMSZ_TOP As Integer = 3
    Const WMSZ_TOPLEFT As Integer = 4
    Const WMSZ_TOPRIGHT As Integer = 5
    Const WMSZ_BOTTOM As Integer = 6
    Const WMSZ_BOTTOMLEFT As Integer = 7
    Const WMSZ_BOTTOMRIGHT As Integer = 8

    If m.Msg = WM_SIZING And m.HWnd.Equals(Me.Handle) Then
        ' Turn the message's lParam into a Rect.
        Dim r As Rect
        r = DirectCast( _
            Marshal.PtrToStructure(m.LParam, _
                GetType(Rect)), _
            Rect)

        ' The first time, save the form's aspect ratio.
        If first_time Then
            first_time = False
            aspect_ratio = (r.bottom - r.top) / (r.right - _
                r.left)
        End If

        ' Get the current dimensions.
        Dim wid As Double = r.right - r.left
        Dim hgt As Double = r.bottom - r.top

        ' Enlarge if necessary to preserve the aspect ratio.
        If hgt / wid > aspect_ratio Then
            ' It's too tall and thin. Make it wider.
            wid = hgt / aspect_ratio
        Else
            ' It's too short and wide. Make it taller.
            hgt = wid * aspect_ratio
        End If

        ' See if the user is dragging the top edge.
        If m.WParam.ToInt32 = WMSZ_TOP Or _
           m.WParam.ToInt32 = WMSZ_TOPLEFT Or _
           m.WParam.ToInt32 = WMSZ_TOPRIGHT _
        Then
            ' Reset the top.
            r.top = r.bottom - CInt(hgt)
        Else
            ' Reset the height to the saved value.
            r.bottom = r.top + CInt(hgt)
        End If

        ' See if the user is dragging the left edge.
        If m.WParam.ToInt32 = WMSZ_LEFT Or _
           m.WParam.ToInt32 = WMSZ_TOPLEFT Or _
           m.WParam.ToInt32 = WMSZ_BOTTOMLEFT _
        Then
            ' Reset the left.
            r.left = r.right - CInt(wid)
        Else
            ' Reset the width to the saved value.
            r.right = r.left + CInt(wid)
        End If

        ' Update the Message object's LParam field.
        Marshal.StructureToPtr(r, m.LParam, True)
    End If

    MyBase.WndProc(m)
End Sub

person SSpoke    schedule 28.06.2013    source источник


Ответы (1)


Вы можете узнать разрешение рабочего стола пользователя с помощью Screen.PrimaryScreen.Bounds.Bottom и Screen.PrimaryScreen.Bounds.Right

person Saulius Šimčikas    schedule 28.06.2013
comment
Да, SystemInformation.VirtualScreen.Width работает так же хорошо. Проблема в том, как исправить приведенный выше код, чтобы он блокировался, когда он достигает предела? потому что он начинает изменять размер без сохранения пропорций, когда срабатывает одно из ограничений, в основном ограничение ширины, но высота, вероятно, также может испортиться в некоторых редких случаях. - person SSpoke; 29.06.2013