Introduction
I recently wrote an application where I needed to use a Skinned interface, and the first thing to do when skinning an application is to remove the Border of a Form by setting:
FormBorderStyle = Windows.Forms.FormBorderStyle.None
Without Border, the main form can attain any shape. But this leaves us with one problem, which is How is the user going to move the Form? So we have to write some custom code to do this, and this is the reason why I wrote a class called MoveFormWithoutBorder
.
A Little Bit About the Code
Global variables which hold the necessary information for moving the form:
Dim WithEvents HookedControl As Windows.Forms.Control
Dim BaseControlToMove As Control
Events
We mainly handle three events of the HookedControl
:
MouseDown
MouseMove
MouseUp
1. MouseDown
At this point, we save the initial location of our form in a global var OffsetLocation
, and then set MoveHook
Boolean Var to True
:
Private Sub Control_MouseDown(ByVal sender As System.Object, _
ByVal e As System.Windows.Forms.MouseEventArgs) _
Handles HookedControl.MouseDown
If Disable = True Then Exit Sub
If e.Button = Windows.Forms.MouseButtons.Left Then
MoveHook = True
OffsetLocation = New Point(e.Location.X, e.Location.Y)
End If
End Sub
2. MouseMove
During this event, the difference is calculated and then added to the Location
of BaseControlToMove
:
Private Sub Control_MouseMove(ByVal sender As Object, _
ByVal e As System.Windows.Forms.MouseEventArgs) Handles HookedControl.MouseMove
If Disable = True Then Exit Sub
If MoveHook = True Then
Dim Newx, NewY As Integer
Newx = e.Location.X - OffsetLocation.X
NewY = e.Location.Y - OffsetLocation.Y
BaseControlToMove.Location = New Point(BaseControlToMove.Location.X + Newx, _
BaseControlToMove.Location.Y + NewY)
End If
End Sub
3. MouseUp
This is the third event that is fired when the user releases the Left Mouse Button. At this point, we clear the Flags MoveHook
and OffsetLocation
, so that the process of moving a form can start all over again.
Private Sub Control_MouseUp(ByVal sender As Object, _
ByVal e As System.Windows.Forms.MouseEventArgs) Handles HookedControl.MouseUp
If Disable = True Then Exit Sub
If e.Button = Windows.Forms.MouseButtons.Left Then
MoveHook = False
OffsetLocation = Nothing
End If
End Sub
Methods
The class exposes two methods to disable or enable the Hook so that the movement can be disabled as required:
Public Sub DisableHook()
Disable = True
MoveHook = False
OffsetLocation.X = 0
OffsetLocation.Y = 0
End Sub
Public Sub EnableHook()
Disable = False
End Sub
Usage
Dim FormMover As MoveFormWithoutBorder = New MoveFormWithoutBorder(Me, Me)
Points of Interest
This class definitely comes in handy when removing the border, and also saves from writing the same code all over again.
History
- 22nd February, 2010: Initial post