1

I posted a question similar to this earlier, however, after thinking about it and testing the answers, I believe I misinterpreted the answers and the answerer(s) misinterpreted me. The original question is here. I think people believed that I just wanted to highlight strings, I didn't state my exact purpose. So, I will now:

What I've been trying to do lately is create a 100% from scratch text box in C++ CLR using GDI+. I've gotten to the challange of placing the caret when the user clicks in the textbox. Doing simple math (Where they clicked divided by line width) I can figure out which line they clicked. But in order to get the character clicked, I need (unless there are better ways) to compare the bounding rectangles of all the characters in the line and place the caret before the one the mouse fits into. In order to do this, I need to get the exact bounds of each individual character, not an entire string.

I've already tried a few things, none of which seemed to work:

I believe I can't use these methods, unless there are ways around their limitations. I hope I made my problem and expected solution a lot more clear than I previously did.

Community
  • 1
  • 1
smoth190
  • 438
  • 7
  • 26

1 Answers1

1

Because of the way text is kerned and anti-aliased, the boundary of a character depends on all of the characters to the left of it. However you don't need to know every character boundary, only the ones on either side of your click point. You can find those with a binary search - split your string in half, measure that (using TextRenderer::MeasureText), and determine if it's to the left or right of your click point. Keep narrowing down the size of the string until there's only one possibility remaining.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • Ok, well if that solves the click problem, what happens when I get to the highlighting problem? The measurements I get above still won't solve my problem with that. – smoth190 Feb 23 '12 at 04:34
  • @smoth190, that's even easier. Just do one measurement of the characters before the highlight, and one with everything up to and including the highlight. – Mark Ransom Feb 23 '12 at 04:42
  • Ok, I guess that seems logical. Thanks for the help, I've just about got this all working. – smoth190 Feb 27 '12 at 20:34