Custom Links in RichTextBox

Suppose each word starting with #generates a double-click event. To do this, I executed the following test code:

private bool IsChannel(Point position, out int start, out int end)
{
    if (richTextBox1.Text.Length == 0)
    {
        start = end = -1;
        return false;
    }

    int index = richTextBox1.GetCharIndexFromPosition(position);
    int stop = index;

    while (index >= 0 && richTextBox1.Text[index] != '#')
    {
        if (richTextBox1.Text[index] == ' ')
        {
            break;
        }
        --index;
    }

    if (index < 0 || richTextBox1.Text[index] != '#')
    {
        start = end = -1;
        return false;
    }

    while (stop < richTextBox1.Text.Length && richTextBox1.Text[stop] != ' ')
    {
        ++stop;
    }
    --stop;

    start = index;
    end = stop;

    return true;
}

private void richTextBox1_MouseMove(object sender, MouseEventArgs e)
{
    textBox1.Text = richTextBox1.GetCharIndexFromPosition(new Point(e.X, e.Y)).ToString();
    int d1, d2;
    if (IsChannel(new Point(e.X, e.Y), out d1, out d2) == true)
    {
        if (richTextBox1.Cursor != Cursors.Hand)
        {
            richTextBox1.Cursor = Cursors.Hand;
        }
    }
    else
    {
        richTextBox1.Cursor = Cursors.Arrow;
    }
}

This handles the detection of words starting with #and making the mouse cursor a hand when it hangs over them. However, I have the following two problems:

  • If I try to implement a double-click event for richTextBox1, I can detect when a word is clicked, however that word is highlighted (selected), which I would like to avoid. I can undo it programmatically by selecting the end of the text, but this causes a flicker, which I would like to avoid. How can this be done?
  • GetCharIndexFromPosition . , , RichTextBox, , #, , , . , , , , ? URL- . URL- www.test.com , , . , . , , .

, - Windows API, , .

Visual Studio 2008, .

Update: , , , . ? , , .

+3
1

(2) :

if (richTextBox1.Text.Length == 0){ ... }

//get the mouse point in client coordinates
Point clientPoint = richTextBox1.PointToClient(richTextBox1.PointToScreen(position));
int index = richTextBox1.GetCharIndexFromPosition(position);
//get the position of the closest char
Point charPoint = richTextBox1.GetPositionFromCharIndex(index);

bool notOnTheSameLine = ((clientPoint.Y < charPoint.Y) || (clientPoint.Y > charPoint.Y + richTextBox1.Font.Height));
bool passedTheWord = (clientPoint.X > charPoint.X + richTextBox1.Font.SizeInPoints);

if (notOnTheSameLine || passedTheWord)
{
  start = end = -1;
  return false;
}


(1) , dbl-click? , cntl-click , ...

+2

Source: https://habr.com/ru/post/1739615/


All Articles