How to make my Windows Form app snap to screen edges?

前端 未结 5 2062
迷失自我
迷失自我 2020-11-29 01:23

Anyone out there know how to make your .net windows form app sticky/snappy like Winamp so it snaps to the edges of the screen?

The target framework would be .NET 2.0

5条回答
  •  情深已故
    2020-11-29 01:44

    https://github.com/stax76/staxrip

    Protected Overrides Sub WndProc(ByRef m As Message)
        Snap(m)
        MyBase.WndProc(m)
    End Sub
    
    Private IsResizing As Boolean
    
    Sub Snap(ByRef m As Message)
        Select Case m.Msg
            Case &H214 'WM_SIZING
                IsResizing = True
            Case &H232 'WM_EXITSIZEMOVE
                IsResizing = False
            Case &H46 'WM_WINDOWPOSCHANGING
                If Not IsResizing Then Snap(m.LParam)
        End Select
    End Sub
    
    Sub Snap(handle As IntPtr)
        Dim workingArea = Screen.FromControl(Me).WorkingArea
        Dim newPos = DirectCast(Marshal.PtrToStructure(handle, GetType(WindowPos)), WindowPos)
        Dim snapMargin = Control.DefaultFont.Height
        Dim border As Integer
        If OSVersion.Current >= OSVersion.Windows8 Then border = (Width - ClientSize.Width) \ 2 - 1
    
        If newPos.Y <> 0 Then
            If Math.Abs(newPos.Y - workingArea.Y) < snapMargin AndAlso Top > newPos.Y Then
                newPos.Y = workingArea.Y
            ElseIf Math.Abs(newPos.Y + Height - (workingArea.Bottom + border)) < snapMargin AndAlso Top < newPos.Y Then
                newPos.Y = (workingArea.Bottom + border) - Height
            End If
        End If
    
        If newPos.X <> 0 Then
            If Math.Abs(newPos.X - (workingArea.X - border)) < snapMargin AndAlso Left > newPos.X Then
                newPos.X = workingArea.X - border
            ElseIf Math.Abs(newPos.X + Width - (workingArea.Right + border)) < snapMargin AndAlso Left < newPos.X Then
                newPos.X = (workingArea.Right + border) - Width
            End If
        End If
    
        Marshal.StructureToPtr(newPos, handle, True)
    End Sub
    

提交回复
热议问题