Introduction
Few months ago, when I needed to make my textbox
draggable and resizable, I searched on the Internet and tried to program it.
This is a simplified code from my Chart-Drawing project. The code just shows a beginner how to move a control by mouse drag and how to resize it at run-time.
About "how to set transparency on textbox background" and "flicker-free moving", I will write in another article.
Feel free to comment. Share to be shared !!!
EDIT: In the last version, I forgot to attach the source, updated.
Background
Click to Add TextBox Button to toggle TextBox Mode, then click to the Panel below, new TextBox will be added to the Panel. The Select Mode Button will toggle Select Mode, add this Mode, you cannot click and add TextBox to Panel.

Using the Code
The main idea of "move by mouse dragging" is using 3 events : MouseDown
, MouseMove
and MouseUp
.
MouseDown
: Set the Flag to TRUE
and save clicked point (Start Point)
MouseMove
: if Flag is TRUE
, change the Location properties of Control (using the distance of Start Point and current mouse location)
MouseUp
: Set the Flag to FALSE
public void SetMoveFunction()
{
bool isDragging = false;
Point StartPoint = Point.Empty;
this.MouseDown += delegate(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isDragging = true;
StartPoint = new Point(e.X, e.Y);
this.Capture = true;
}
};
this.MouseUp += delegate(object sender, MouseEventArgs e)
{
this.Cursor = Cursors.Arrow;
isDragging = false;
this.Capture = false;
};
this.MouseMove += delegate(object sender, MouseEventArgs e)
{
if (isDragging)
{
this.Cursor = Cursors.NoMove2D;
this.Left = Math.Max(0, e.X + this.Left - StartPoint.X);
this.Top = Math.Max(0, e.Y + this.Top - StartPoint.Y);
}
};
}
As you see, I wrote a method which called delegate of control's MouseDown
-MouseUp
-MouseMove
events. So, in the Constructor
class, just call SetMoveFunction()
and your control is draggable. :D
this.Capture = true;
This is a trick! Control.Capture
property receives mouse input whether or not the cursor is within control's borders. It will make the dragging operation smoother. But remember to set it back to FALSE
when dragging is over.
Next is a resize function. The main idea is add 8 square label to control (Handles), the handles location will be: east, west, south, north, northeast, northwest, southeast, southwest.
When the user "moves" (by dragging) the handle, it will move and the size of control will be set based on handle location. These methods are written at Resize Methods region in the source. Please download the source and feel free to comment if you have any questions.
