Fatal Shocks

May 14, 2007

How to get the Caret Position in a TextBox/TextArea using C#

Filed under: Uncategorized — Hasan Maqbool @ 6:58 am

I have been in an ultimate need of having the curson position (more appropriately caret postion) for an Urdu Auto Complete Text Aea. Finally, after a little R&D i came up with a solution. Have a look of the solution.

what I had to do is,

Import the System.Runtime.InteropServices and import the user32.dll as follows.


private static extern int getCaretPos(ref Point pt);

After importing the dll, next step is to make a method which uses this imported dll to have the cursor position.

For example, I made the method as follows


public Point GetCaretXYPosition

Point pt = Point.Empty;
GetCaretPos(ref pt);
//I have commented as i was my requirement. Not necessarily, it will be required by everyone.

//pt.X -= 100;
//pt.Y += 20;

return pt;

Thats it, it is all about how to get the cursor posistion in a TextBox/TextArea.


Blog at WordPress.com.