Dragging and dropping text can be helpful to rearrange large portions of text. It is a very easy way to move text around in word processing applications.
TX Text Control provides all the events needed to implement this behavior. This sample uses 3 different events to control drag and drop: MouseDown, MouseUp and MouseMove.
On the MouseUp event, the selected text is stored in a separate Selection object that holds the currently selected text, it's character index start position and length.
private void textControl1_MouseUp(object sender, MouseEventArgs e)
{
if (dragAction == false)
{
fillSyncSelection();
}
...private void fillSyncSelection()
{
syncSelection.Start = textControl1.Selection.Start;
syncSelection.Length = textControl1.Selection.Length;
syncSelection.Text = textControl1.Selection.Text;
}If the user clicks into the selected text, a boolean flag is activated. This flag indicates that a drag and drop action is currently being performed:
private void textControl1_MouseDown(object sender, MouseEventArgs e)
{
if (syncSelection.Length > 0 && (textControl1.Selection.Start >=
syncSelection.Start && textControl1.Selection.Start <=
syncSelection.Start + syncSelection.Length))
{
dragAction = true;
textControl1.CaretWidth = 2;
}
}In the MouseMove event, the input position is set to the current mouse position.
private void textControl1_MouseMove(object sender, MouseEventArgs e)
{
if( dragAction == true)
{
textControl1.Selection.Length = 0;
textControl1.InputPosition = new TXTextControl.InputPosition(new Point((e.X * DPIX) +
textControl1.ScrollLocation.X, (e.Y * DPIX) +
textControl1.ScrollLocation.Y));
}
}When the mouse button is released again, the selected text is copied to the current input position and removed from the original position:
private void textControl1_MouseUp(object sender, MouseEventArgs e)
{
...
else
{
int start = syncSelection.Start;
if (textControl1.Selection.Start < syncSelection.Start)
{
start = syncSelection.Start + syncSelection.Text.Length;
}
textControl1.Selection.Text = syncSelection.Text;
int inputPos = textControl1.Selection.Start;
textControl1.Select(start, syncSelection.Length);
textControl1.Selection.Text = "";
textControl1.Selection.Start = inputPos;
textControl1.CaretWidth = 1;
syncSelection = new TXTextControl.Selection();
dragAction = false;
}
}The minimum requirements for this sample application are TX Text Control .NET trial version and Visual Studio 2005.