In the Winform form, drag the mouse to change the position of the control. During the drag process, a black box with the same size as the dragged control is displayed with the mouse following to simulate the drag effect. For example, the following is the source code. A Button control is dragged here. If needed, you can also change the cursor when dragging.
/Files/tssing/FormDrag.rar
Code
Using System;
Using System. Collections. Generic;
Using System. ComponentModel;
Using System. Data;
Using System. Drawing;
Using System. Linq;
Using System. Text;
Using System. Windows. Forms;
Namespace FormDrag
{
Public partial class Form1: Form
{
Public Form1 ()
{
InitializeComponent ();
}
Private Control control;
Private void Form1_Load (object sender, EventArgs e)
{
This. Paint + = new System. Windows. Forms. PaintEventHandler (this. FormDrag_Paint );
Control = new Button ();
Control. MouseDown + = new MouseEventHandler (control_MouseDown );
Control. MouseMove + = new MouseEventHandler (control_MouseMove );
Control. MouseUp + = new MouseEventHandler (control_MouseUp );
This. Controls. Add (control );
}
// Press the coordinates of the mouse (the relative coordinates of the control)
Point mouseDownPoint = Point. Empty;
// Display the rectangle of the drag effect
Rectangle rect = Rectangle. Empty;
// Drag or drop
Bool isDrag = false;
Void control_MouseDown (object sender, MouseEventArgs e)
{
If (e. Button = MouseButtons. Left)
{
MouseDownPoint = e. Location;
// Record the widget size
Rect = control. Bounds;
}
}
Void control_MouseMove (object sender, MouseEventArgs e)
{
If (e. Button = MouseButtons. Left)
{
IsDrag = true;
// Reset the rect position and move the cursor
Rect. Location = getPointToForm (new Point (e. Location. X-mouseDownPoint. X, e. Location. Y-mouseDownPoint. Y ));
This. Refresh ();
}
}
Void control_MouseUp (object sender, MouseEventArgs e)
{
If (e. Button = MouseButtons. Left)
{
If (isDrag)
{
IsDrag = false;
// Move the control to the place where the mouse is opened
Control. Location = rect. Location;
This. Refresh ();
}
Reset ();
}
}
// Reset the variable
Private void reset ()
{
MouseDownPoint = Point. Empty;
Rect = Rectangle. Empty;
IsDrag = false;
}
// Screen weight
Private void FormDrag_Paint (object sender, PaintEventArgs e)
{
If (rect! = Rectangle. Empty)
{
If (isDrag)
{// Draw a black box of the same size as the Control
E. Graphics. DrawRectangle (Pens. Black, rect );
}
Else
{
E. Graphics. DrawRectangle (new Pen (this. BackColor), rect );
}
}
}
// Convert the coordinates of the control to those of the form.
Private Point getPointToForm (Point p)
{
Return this. PointToClient (control. PointToScreen (p ));
}
}
}