Microsoft Communities

Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I allow the user to drag a window if it doesn't have a title bar or border?

You can drag such a window by using Win32 APIs to switch the mouse hit to WM_NCLBUTTONDOWN. The code below will allow you to drag by mousing down anywhere in the form's clientarea as long as you don't hit a child control on the form.

using System.Runtime.InteropServices;
using System.Windows.Forms;

public const int WM_NCLBUTTONDOWN = 0xa1; 
public const int HTCAPTION = 0x02; 

[ DllImport("user32.dll") ] 
public static extern int SendMessage( IntPtr hWnd, int Msg, int wParam, int lParam ); 

[ DllImport("user32.dll") ] 
public static extern bool ReleaseCapture(); 

private void Form1_MouseDown( object sender, MouseEventArgs e ) 
{ 
  ReleaseCapture(); 
  SendMessage( Handle, WM_NCLBUTTONDOWN, HTCAPTION, 0 ); 
}

Here is a solution that does not rely on InteropServices.

Private blnMoving As Boolean = False
Private MouseDownX As Integer
Private MouseDownY As Integer

Private Sub Form1_MouseDown(ByVal sender As Object, _
    ByVal e As MouseEventArgs) Handles Form1.MouseDown
  If e.Button = MouseButtons.Left Then
    blnMoving = True
    MouseDownX = e.X
    MouseDownY = e.Y
  End If
End Sub

Private Sub Form1_MouseUp(ByVal sender As Object, _
    ByVal e As MouseEventArgs) Handles Form1.MouseUp
  If e.Button = MouseButtons.Left Then
    blnMoving = False
  End If
End Sub

Private Sub Form1_MouseMove(ByVal sender As Object, _
    ByVal e As MouseEventArgs) Handles Form1.MouseMove
  If blnMoving Then
    Dim temp As Point = New Point
    temp.X = Form1.Location.X + (e.X - MouseDownX)
    temp.Y = Form1.Location.Y + (e.Y - MouseDownY)
    Form1.Location = temp
  End If
End Sub

George Shepherd, Syncfusion, and Jacob Grass, Abiliti Solutions



Page view counter