Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

A simple way to snap a form to screen borders

0.00/5 (No votes)
22 Dec 2007 1  
A simple way to snap a form without borders to the screen.

Background

I was searching for a way to snap a form to the borders of the screen, like what WinAmp does, and found one here. But my form was without border (FormBorderStyle = None), and the code I found here didn't work great for forms without border. It also seemed like a little complicated for beginners (almost like me!), so I tried to write it myself, and wrote a more simple and easy to understand code. This is also a very simple way to move forms without border.

Code

The following variables should be declared right after Public Class ... so that other procedures can access them.

Dim X1 As Integer, Y1 As Integer, WR As Rectangle

Now put the following code in the MouseDown event of the form:

Private Sub Form1_MouseDown(ByVal sender As Object, _
            ByVal e As System.Windows.Forms.MouseEventArgs) _
            Handles Me.MouseDown
   X1 = e.X
   Y1 = e.Y
   WR = Screen.GetWorkingArea(Me)
End Sub

This piece of code records the point where the mouse was clicked and also the working area of the desktop. Now the main part of the code should be put in the MouseMove event of the form.

Private Sub Form1_MouseMove(ByVal sender As Object, _
            ByVal e As System.Windows.Forms.MouseEventArgs) _
            Handles Me.MouseMove
   If Not e.Button = Windows.Forms.MouseButtons.Left Then Exit Sub
   Dim NewX As Integer = Me.Left + (e.X - X1)
   Dim NewY As Integer = Me.Top + (e.Y - Y1)
   Dim W As Integer = Me.Width
   Dim H As Integer = Me.Height
   If NewY >= WR.Top - 15 And NewY <= WR.Top + 15 Then
      Me.Top = WR.Top
   ElseIf NewY + H > WR.Bottom - 15 And NewY + H < WR.Bottom + 15 Then
      Me.Top = WR.Bottom - H
   Else
      Me.Top = NewY
   End If
   If NewX >= WR.Left - 15 And NewX <= WR.Left + 15 Then
      Me.Left = WR.Left
   ElseIf NewX + W > WR.Right - 15 And NewX + W < WR.Right + 15 Then
      Me.Left = WR.Right - W
   Else
      Me.Left = NewX
   End If
End Sub

This code calculates the new position of the form when you move the mouse with left button pressed down, and snaps it when it gets near the borders of the screen. The default distance is 15, but you can change it, or replace it with a variable to change it dynamically during runtime.

Significance

It is a very easy to understand code and has no complications. It also uses a very simple method to move a form which has no border.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here