Guillermo

Guillermo

  • NA
  • 3
  • 6.5k

Select text in a rich text box on right click

Apr 20 2011 12:07 PM
Hi,

I'm trying to set up spell checking in a richtextbox, where right clicking on a misspelled word will bring up a menu of suggested words. In order for this to work, the text cursor needs to be inside/adjacent to the word, which currently requires left-clicking to move the cursor there, and then right-clicking to bring up the menu. I would like to make it so on right click, it places the text cursor and selects the text (as if it had been a left click) and also brings up the menu. I tried the following:

using System.Runtime.InteropServices;

private const UInt32 MOUSEEVENTF_LEFTDOWN = 0x0002;
private const UInt32 MOUSEEVENTF_LEFTUP = 0x0004;

[DllImport("user32.dll")]
private static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, uint dwExtraInf);

private void richtextbox1_MouseDown(object sender, MouseEventArgs e) {

mouse_event(MOUSEEVENTF_LEFTDOWN, (uint)Cursor.Position.X, (uint)Cursor.Position.Y, 0, 0);//make left button down
mouse_event(MOUSEEVENTF_LEFTUP, (uint)Cursor.Position.X, (uint)Cursor.Position.Y, 0, 0);//make left button up


This simulates a left-click. It brings the text cursor to the appropriate location, but it doesn't update the richtextbox1.SelectionStart value, which is needed to determine which word it is. Any ideas? If there's a dirty way to accurately calculate the selection index using the mouse position, I'd be okay with that.

Answers (3)