Click here to Skip to main content
15,868,119 members
Articles / Programming Languages / Visual Basic

Moving a Window

Rate me:
Please Sign up or sign in to vote.
1.52/5 (8 votes)
10 Jul 2006CPOL 26.6K   128   10   1
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:

VB
Imports System.Runtime.InteropServices

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

VB
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:

VB
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 1 Pin
babakzawari24-Sep-10 3:50
babakzawari24-Sep-10 3:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.