Click here to Skip to main content
15,879,096 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hello. I have to get Coordinates of Caret in richtextbox C# but I don't know how to get it! I want get the x coordinate and the y coordinate of it.
I hope you can Help me!
Thank you very much!
Posted
Comments
Toli Cuturicu 24-Mar-11 10:11am    
Google?
ck47ht 24-Mar-11 10:19am    
what?
#realJSOP 24-Mar-11 14:17pm    
He said, "Google?"
ck47ht 24-Mar-11 10:21am    
I want get Coordinates of Caret in richtextbox C#
who can help me?
OriginalGriff 24-Mar-11 10:30am    
Reason for my vote of one: Far too lazy to google.

Griff's Answer is correct, but only for WPF.

For System.Windows.Forms it is more tricky. The position in text is defined by System.Windows.Forms.RichTextBox.SelectionStart. This is a character index. You probably need a line number and position in line. For this purpose, first use GetLineFromCharIndex; it will give you the line. When you know the line, use GetFirstCharIndexFromLine to get the character index again. The difference between your original character index and the character index at the beginning of the line will calculate the position in the line, that is, a column. See other System.Windows.Forms.RichTextBox.Get... methods for more information.

In addition to Griff's Answer: for WPF, CaretPosition will return an instance of TextPointer. Use this class to find out the line and position in line.

—SA
 
Share this answer
 
Comments
OriginalGriff 24-Mar-11 15:45pm    
Yep! You are right, I forgot that: I answered this same question a few weeks ago and it slipped my mind! :doh:
Sergey Alexandrovich Kryukov 24-Mar-11 15:47pm    
No problem: how about some teamwork?
Thank you, Griff.
--SA
Toli was suggesting that perhaps, if you used Google, you might have found the solution to this a while ago.

Perhaps a complicated google: "Richtextbox caret position" might help.

It put this at the top of the list: http://msdn.microsoft.com/en-us/library/system.windows.controls.richtextbox.caretposition(v=vs.90).aspx[^] when I tried it...

Next time, don't be so lazy!
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 24-Mar-11 14:17pm    
Griff, this is correct, my 5, but only for WPF. For Forms, it would need some (minimal) thinking.
Please see my Answer with adds to yours.
--SA
#realJSOP 24-Mar-11 14:18pm    
NO WAY!!! GOOGLE!!!??? WTF?!?!?!?!
OriginalGriff 24-Mar-11 15:46pm    
Take a virtual 5!
Sergey Alexandrovich Kryukov 24-Mar-11 15:48pm    
Can I up-vote this shouting? :-)
--SA
supernorb 10-Mar-13 21:14pm    
I think you shouted a wrong word, WPF not WTF =)))

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900