Highlighting text in a Winforms textbox

123 views Asked by At

For a Winforms textbox, when you click and drag over the text, it highlights it. Is there a way to determine which direction the user dragged over?

1

There are 1 answers

0
Special Sauce On

There is no way to get this info using the Windows TextBox selection API. For example, the EM_GETSEL message defines the starting and ending character positions of the selection, but in a predefined (sorted) order.

However you could get this info by handling the control's MouseMove event. For example:

textBox1.MouseMove += new MouseEventHandler(textBox1_MouseMove);

void textBox1_MouseMove(object sender, MouseEventArgs e)
{
    Control tbCtrl = sender as Control;
    // the mouse coordinate values here are relative to the coordinates of the control that raised the event
    int mouseX = e.X;
    ...
}

By applying some logic to mouseX you could potentially discover the average direction the cursor is moving. It would work best if the user is making a linear motion. You could also handle the textbox's drag-and-drop event for similar mouse information if you only wanted the event raised while the user was dragging the mouse.