Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/263.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 当鼠标悬停在RichTextBox中的文本上时,如何创建新事件?_C#_Winforms_Events_Richtextbox_Mousehover - Fatal编程技术网

C# 当鼠标悬停在RichTextBox中的文本上时,如何创建新事件?

C# 当鼠标悬停在RichTextBox中的文本上时,如何创建新事件?,c#,winforms,events,richtextbox,mousehover,C#,Winforms,Events,Richtextbox,Mousehover,我有一个RichTextBox,它包含一个字符串,例如:“Hello”,我想在鼠标悬停在“Hello”这个词上时创建一个新事件,或者为了简化这一点,在鼠标悬停在“Hello”这个词上时显示一个消息框。那么如何实现这一点呢?请确保将事件“richTextBox1_MouseHover”连接到富文本框的悬停位置 private void richTextBox1_MouseHover(object sender, EventArgs e) { MessageBox.Show("Hello")

我有一个
RichTextBox
,它包含一个字符串,例如:“Hello”,我想在鼠标悬停在“Hello”这个词上时创建一个新事件,或者为了简化这一点,在鼠标悬停在“Hello”这个词上时显示一个消息框。那么如何实现这一点呢?

请确保将事件“richTextBox1_MouseHover”连接到富文本框的悬停位置

private void richTextBox1_MouseHover(object sender, EventArgs e)
{
    MessageBox.Show("Hello");
}

我想你可以用这个来实现这一点。有些人试图实现类似的目标。看一看。

首先,让我们定义一个方法,获取最靠近光标的单词:

public static class Helper
{
    public static string GetWordUnderCursor(RichTextBox control, MouseEventArgs e)
    {
        //check if there's any text entered
        if (string.IsNullOrWhiteSpace(control.Text))
            return null;
        //get index of nearest character
        var index = control.GetCharIndexFromPosition(e.Location);
        //check if mouse is above a word (non-whitespace character)
        if (char.IsWhiteSpace(control.Text[index]))
            return null;
        //find the start index of the word
        var start = index;
        while (start > 0 && !char.IsWhiteSpace(control.Text[start - 1]))
            start--;
        //find the end index of the word
        var end = index;
        while (end < control.Text.Length - 1 && !char.IsWhiteSpace(control.Text[end + 1]))
            end++;
        //get and return the whole word
        return control.Text.Substring(start, end - start + 1);
    }
}
但是,在我看来,最好让
RichTextBox
正常引发
MouseMove
事件,并且只有在满足条件时才采取行动。为此,您只需注册
MouseMove
处理程序并检查以下条件:

private void richTextBox1_MouseMove(object sender, MouseEventArgs e)
{
    var control = sender as RichTextBox;
    //get the word under the cursor
    var word = Helper.GetWordUnderCursor(control, e);
    if (string.Equals(word, "Hello"))
    {
        //do your stuff
    }
}

谢谢,但我想在将鼠标悬停在特定字符串上时创建该事件,而不是在整个RichTextBox上。
private void richTextBox1_MouseMove(object sender, MouseEventArgs e)
{
    var control = sender as RichTextBox;
    //get the word under the cursor
    var word = Helper.GetWordUnderCursor(control, e);
    if (string.Equals(word, "Hello"))
    {
        //do your stuff
    }
}