Making the caret follow the mouse cursor in a textbox

telmessos

New member
Joined
Oct 31, 2012
Messages
2
Programming Experience
3-5
Hi all,

I am writing a text editor. I need to make the following things to be working:

1) Caret of the textbox, follow the mouse cursor when the left mouse button is pressed and the mouse cursor is on the textbox. (This is for the drag drop function. I want to drag and drop treeview items to the mouse cursor position)
2) If the mouse cursor location is on the text box but out of the caret line areas (For example: if there are two lines of code if I keep the mouse on the third or higher number of lines), I want the value added to the end of the text and caret position comes to the end of the text.

I will appreciate if anyone can help about this problem.

Kindest Regards
 
You can look at the Control.MousePosition property to get the mouse pointer location in screen coordinates. You can the use the PointToClient method of your control to convert that to client coordinates. The GetCharIndexFromPosition method of your TextBox will then give you a location to set the caret, which you can do by setting the SelectionStart property.

I'm not sure what GetCharIndexFromPosition will do if the position is below the last line. I don't know whether it will just look straight up to find the closest character or if it will go to the last character in the text. You can find out by testing. If it's the latter then you're fine as is. If it's the former then you will have to do a bit of work. You can use GetPositionFromCharIndex to see what the Y position of the last character is and then see if the mouse location is below that. If it is then you can just use the index of the last character regardless.
 
Back
Top Bottom