views:

30

answers:

1

I created a modeless find dialog for use in searching in a RichTextBox and am having trouble positioning the find dialog after the found text is selected so that it does not cover the selected text. I have tried to get the line number relative to the client area using the following:

this.lineCount = this.rtb.Height / (this.rtb.Font.Height+2);

rtb.Select(rtbIndex, searchText.Length);

int linePos = (this.rtb.GetLineFromCharIndex(this.rtb.GetFirstCharIndexOfCurrentLine())) % this.lineCount;

if(linePos<(this.lineCount/2))
{
    this.Location = rtb.PointToScreen(new Point(rtb.Bounds.Left, rtb.Bounds.Bottom - this.Height));
}
else
{
    this.Location = rtb.PointToScreen(new Point(rtb.Bounds.Left, rtb.Bounds.Top));
}

this.lineCount is the number of lines that fit in the client area based on the font height and the height of the richtextbox. It is an accurate value that I have verified. My code positions the find dialog at the bottom of the richtextbox if lineNum is less than half the value of this.lineCount, otherwise at the top

Hoewever, linePos is not reliable. It sometimes has a value of zero when the line with the selected text is the 19th line and the lineCount is 20, so the dialog gets moved over the selected text. Thus it does not reliably calcualte where the richtextbox displays the selected text.

+1  A: 

You don't need to calculate the character position yourself, you can get it using the GetPositionFromCharIndex method

Thomas Levesque
but that does not help position the dialog so it does not cover the selected text because it gives the absolute position from the beginning of the text in the RTB, not relative to the displayed text, which is what I need.
bill seacham
@bill, I'm not sure what's happening on your end. `GetPositionFromCharIndex` returns coordinates relative to the top-left corner of the RTB regardless of scroll position. (I double-checked by creating a VS 2010 WinForms project targeted for .Net 2.0, running on Win7.)