RichTextBox: Getting Line Number following a Right Click

robertb_NZ

Well-known member
Joined
May 11, 2010
Messages
146
Location
Auckland, New Zealand
Programming Experience
10+
I am trying to implement contextual Help for a RichTextBox, and I need to know the text that was right-clicked. I can find this out for a normal click using
HelpLineNbr = RTB.GetLineFromCharIndex(RTB.SelectionStart)
HelpLineStart = RTB.GetFirstCharIndexOfCurrentLine()

However SelectionStart is not set if the user right-clicks, with this code returning the position of the preceding normal click.

How do I get this to be work with a right click?

Thank you, Robert Barnes
 
You would handle the MouseClick event, which is raised for any mouse button click and also provides the coordinates of the click. You can call GetCharIndexFromPosition and then use the result in place of SelectionStart in your existing code.
 
Thank you for this. The key change is using GetCharIndexFromPosition instead of SelectionStart. I couldn't make this work with MouseClick, so I stuck with MouseUp. My code is: -

Private Sub RTB_MouseUp(ByVal Sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles RTB.MouseUp

'Checking the Mouse right Button
If e.Button = MouseButtons.Right Then
' Context menu for Help
Dim cxtMenu As New ContextMenu()
Dim mnuHelp As New MenuItem
Me.ContextMenu = cxtMenu
mnuHelp.Text = "&Help"
cxtMenu.MenuItems.Add(mnuHelp)
AddHandler mnuHelp.Click, AddressOf mnuHelp_Click
HelpPoint = New Point(e.X, e.Y)
HelpLineNbr = RTB.GetLineFromCharIndex(RTB.SelectionStart) ' Gives the wrong result (Statement now removed of course)
HelpLineNbr = RTB.GetLineFromCharIndex(RTB.GetCharIndexFromPosition(HelpPoint)) ' Gives the correct Result
Me.ContextMenu.Show(RTB, HelpPoint)
End If
End Sub

Clicking the Help button fires up my mnuHelp_Click handler, so now all I have to do is to figure out what to actually do for Help. This should be straightforward, I hope.

Thank you, Robert.
 
Back
Top