gmbc
gmbc

Reputation: 1

Determine which line is clicked in richtextbox

I'm relatively new to windows forms and am currently making and application, but I've ran into a problem. I wish to determine which line is clicked in a rich text box. I'm using the following code:

private void richTextBox1_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
            {
                var charPosition = richTextBox1.GetCharIndexFromPosition(Mouse.GetPosition(richTextBox1));
                var linePosition = richTextBox1.GetLineFromCharIndex(charPosition);
            }
        }

The only part I can't seem to figure out is the relativeTo argument (cannot convert from 'System.Windows.Forms.RichTextBox' to 'System.Windows.IInputElement' error). What should I do?

Upvotes: 0

Views: 818

Answers (1)

LarsTech
LarsTech

Reputation: 81610

If you are using WinForms (looks suspect), use the MouseDown event:

private void RichTextBox1_MouseDown(object sender, MouseEventArgs e)
{
  if (e.Button == MouseButtons.Left)
  {
    int p = richTextBox1.GetCharIndexFromPosition(e.Location);
    int line = richTextBox1.GetLineFromCharIndex(p);
    // code...
  }
}

Upvotes: 1

Related Questions