将鼠标悬停在RichTextBox中的文本上时如何制作新事件?

时间:2014-11-30 07:42:24

标签: c# winforms events richtextbox mousehover

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

3 个答案:

答案 0 :(得分:2)

首先,让我们定义一个方法,使单词最接近光标:

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);
    }
}

如果光标位于MouseMove之上并且最近的单词为RichTextBox,则仅为了引发"Hello"事件,您需要定义自己的控件来自{{1}并覆盖RichTextBox方法,并在表单中使用它OnMouseMove

RichTextBox

但是,在我看来,让public class MyRichTextBox : RichTextBox { protected override void OnMouseMove(MouseEventArgs e) { //get the word under the cursor var word = Helper.GetWordUnderCursor(this, e); if (string.Equals(word, "Hello")) { //let RichTextBox raise the event base.OnMouseMove(e); } } } 正常提升RichTextBox事件并在条件得到满足时采取行动会更好。为此,您只需注册MouseMove处理程序并检查条件:

MouseMove

答案 1 :(得分:0)

我认为您可以使用Cursor class来实现这一目标。有些人试图达到类似的目的。看看here

答案 2 :(得分:-1)

确保您有一个事件'richTextBox1_MouseHover'连接到Rich Text Box的悬停。

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