65.9K
CodeProject is changing. Read more.
Home

Moving a Window

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.52/5 (8 votes)

Jul 11, 2006

CPOL
viewsIcon

26969

downloadIcon

128

Simple code for moving a window using Win32 API in .NET.

Introduction

Design your own forms with movement enabled. You can even add functionality for maximizing, minimizing, and restoring a form. The code below gives you a brief explanation, and you can just copy paste it in your form code.

You have to import System.Runtime.InteropServices in order to declare Win32 API functions:

Imports System.Runtime.InteropServices

In the beginning of the form code, declare all the constants and APIs:

Public Const GWL_STYLE = (-16)
Public Const WS_DLGFRAME = &H400000
Public Const HTCAPTION = 2
Public Const WM_NCLBUTTONDOWN = &HA1

Public Const SW_HIDE = 0
Public Const SW_MAXIMIZE = 3
Public Const SW_MINIMIZE = 6
Public Const SW_RESTORE = 9

<DllImport("User32.dll")> _
Public Shared Function ShowWindow(ByVal hWnd As IntPtr, _
              ByVal nCmdShow As Integer) As Integer
End Function

<DllImport("User32.dll")> _
Public Shared Function ReleaseCapture() As Integer
End Function

<DllImport("User32.dll")> _
Public Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal wMsg As Integer, _
              ByVal wParam As Integer, ByVal lParam As Integer) As Integer
End Function

Paste this code in the mouse-down event of the form:

If e.Button = Windows.Forms.MouseButtons.Left Then
    Me.Cursor = Cursors.SizeAll
    Call ReleaseCapture()
    Call SendMessage(Me.Handle, WM_NCLBUTTONDOWN, HTCAPTION, 0&)
    Me.Cursor = Cursors.Arrow
End If

Download the source code to view the entire code.