1. Home
  2. Computing & Technology
  3. Visual Basic

Create Forms in Any Shape!

Dragging the Form to a New Location

By Dan Mabbutt, About.com

Oct 20 2007

One of the problems with the program above is that the "form" can't be moved around like a regular form. There's no title bar to use to drag the form. It's possible to use a Windows API call to send a command to Windows that simulates the action of a title bar, however.

To solve this problem, I added a Button to the form to use to drag it around. You could use a lot of different things as long as the component supports an event that can be used to send the right API call to Windows. You don't need to call a Windows API very often in VB.NET, but this is one of those times.

The basic idea is to send a "message" to Windows and tell it that the left mouse button is down and that the title area of the form was clicked. The fact that a button was clicked instead doesn't matter. Windows believes what you tell it.

To do this, you first have to code two "magic number" constants that have to be in the message sent to Windows. Put them right after the Class declaration.

' Indicates the form caption
Const HT_CAPTION As Integer = &H2
' Windows Message Non Client Button Down
Const WM_NCLBUTTONDOWN As Integer = &HA1

These magic numbers are what makes native Windows programming hard. There's a zillion of them and knowing just the right one is critical. The best reference I know of remains Dan Appleman's book, A Guide to the Win32 API. (My copy was published in 1999.) The article linked above reviews the book and also tells you something about how to make calls to a Win32 API. It's somewhat dated since it was written for VB 6 but you can get the main concept.

The call to the API looks a bit different in VB.NET. To finish the job, add this code for the Button MouseDown event:

Private Sub Button1_MouseDown( _
   ByVal sender As Object, _
   ByVal e As System.Windows.Forms.MouseEventArgs) _
   Handles Button1.MouseDown
   If e.Button = Windows.Forms.MouseButtons.Left Then
      Button1.Capture = False
      Me.WndProc(Message.Create(Me.Handle, WM_NCLBUTTONDOWN, _
      CType(HT_CAPTION, IntPtr), IntPtr.Zero))
   End If
End Sub

The statement ...

Button1.Capture = False

... is necessary or Windows will ignore the API call. A review of Microsoft's documentation helps here:

"When a control has captured the mouse, it receives mouse input whether or not the cursor is within its borders. The mouse is typically only captured during drag operations."

On the next page, we make the form look even better by adding a non-rectangular image to the background.

Explore Visual Basic

More from About.com

  1. Home
  2. Computing & Technology
  3. Visual Basic
  4. Using VB.NET
  5. Create Forms in Any Shape!

©2008 About.com, a part of The New York Times Company.

All rights reserved.