在鼠标悬停的文本上显示工具提示。

时间:2021-07-04 19:44:17

I want to display a tooltip when the mouse hovers over a link in my custom rich edit control. Consider the following text:

当鼠标悬停在我自定义丰富的编辑控件中的链接时,我想显示一个工具提示。考虑以下文本:

We all sleep at night .

我们都在晚上睡觉。

In my case the word sleep is a link.

在我看来,睡眠这个词是一种联系。

When the user moves the mouse under the link, in this case "sleep", I want to display a tooltip for the link.

当用户在链接下移动鼠标时,在这种情况下“sleep”,我想要显示一个链接的工具提示。

The following came to my mind, but they are not working

下面是我的想法,但是他们不工作。

1) Trapping OnMouseHover

1)捕获OnMouseHover

if(this.Cursor == Cursors.Hand)
   tooltip.Show(textbox,"My tooltip");
else
   tooltip.Hide(textbox);

But this does not work out.

但这并不奏效。

UPDATE

更新

The links mentioned are not URLs, i.e these are custom links, so Regex won't be of much help here, it can be any text. The user can choose to create it a a link.

所提到的链接不是url,我。这些是自定义链接,所以Regex在这里不会有多大帮助,它可以是任何文本。用户可以选择创建一个链接。

Though I have not tried GetPosition method, I dont think it would be that elegant in terms of design and maintenance.

虽然我没有尝试过GetPosition方法,但我认为在设计和维护方面它不会那么优雅。

Let me say I have the following line, in my richedit box

我有下面一行,在我的richedit框中。

We sleep at night. But the bats stay awake. Cockroaches become active at night.

我们在晚上睡觉。但是蝙蝠保持清醒。蟑螂在晚上变得活跃。

In the above sentence, I want three different tooltips, when the mouse hovers over them.

在上面的句子中,我想要三个不同的工具提示,当鼠标悬停在它们上面的时候。

sleep -> Human beings
awake -> Nightwatchman here
active -> My day begins

I trapped OnMouseMove as follows:

我被困住了。

Working- with Messagebox

工作——弹出窗口

OnMouseMove( )
{

   // check to see if the cursor is over a link
   // though this is not the correct approach, I am worried why does not a tooltip show up
   if(this.Cursor.current == Cursors.hand )
   {
     Messagebox.show("you are under a link");
   }
}

Not Working - with Tooltip - Tooltip does not show up

不使用工具提示-工具提示没有显示。

OnMouseMove( MouseventArgs e )
{

   if(cursor.current == cursors.hand )
   {
     tooltip.show(richeditbox,e.x,e.y,1000);
   }
}

9 个解决方案

#1


12  

Well, take a look, this works, If you have problems please tell me:

嗯,看一看,如果你有问题,请告诉我:

using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1() { InitializeComponent(); }

        ToolTip tip = new ToolTip();
        void richTextBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (!timer1.Enabled)
            {
                string link = GetWord(richTextBox1.Text, richTextBox1.GetCharIndexFromPosition(e.Location));
                //Checks whether the current word i a URL, change the regex to whatever you want, I found it on www.regexlib.com.
//you could also check if current word is bold, underlined etc. but I didn't dig into it.
                if (System.Text.RegularExpressions.Regex.IsMatch(link, @"^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*$"))
                {
                    tip.ToolTipTitle = link;
                    Point p = richTextBox1.Location;
                    tip.Show(link, this, p.X + e.X,
                        p.Y + e.Y + 32, //You can change it (the 35) to the tooltip's height - controls the tooltips position.
                        1000);
                    timer1.Enabled = true;
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e) //The timer is to control the tooltip, it shouldn't redraw on each mouse move.
        {
            timer1.Enabled = false;
        }

        public static string GetWord(string input, int position) //Extracts the whole word the mouse is currently focused on.
        {
            char s = input[position];
            int sp1 = 0, sp2 = input.Length;
            for (int i = position; i > 0; i--)
            {
                char ch = input[i];
                if (ch == ' ' || ch == '\n')
                {
                    sp1 = i;
                    break;
                }
            }

            for (int i = position; i < input.Length; i++)
            {
                char ch = input[i];
                if (ch == ' ' || ch == '\n')
                {
                    sp2 = i;
                    break;
                }
            }

            return input.Substring(sp1, sp2 - sp1).Replace("\n", "");
        }
    }
}

#2


9  

Just add ToolTip tool from toolbox to the form and add this code in a mousemove event of any control you want to make the tooltip start on its mousemove

只需将ToolTip工具从工具箱添加到表单,并将此代码添加到任何控件的mousemove事件中,您希望将工具提示从它的mousemove上启动。

private void textBox3_MouseMove(object sender, MouseEventArgs e)
    {
      toolTip1.SetToolTip(textBox3,"Tooltip text"); // you can change the first parameter (textbox3) on any control you wanna focus
    }

hope it helps

希望它能帮助

peace

和平

#3


4  

You shouldn't use the control private tooltip, but the form one. This example works well:

您不应该使用控件私有工具提示,而是使用表单。这个例子的作品:

public partial class Form1 : Form
{
    private System.Windows.Forms.ToolTip toolTip1;

    public Form1()
    {
        InitializeComponent();
        this.components = new System.ComponentModel.Container();
        this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);

        MyRitchTextBox myRTB = new MyRitchTextBox();
        this.Controls.Add(myRTB);

        myRTB.Location = new Point(10, 10);
        myRTB.MouseEnter += new EventHandler(myRTB_MouseEnter);
        myRTB.MouseLeave += new EventHandler(myRTB_MouseLeave);
    }


    void myRTB_MouseEnter(object sender, EventArgs e)
    {
        MyRitchTextBox rtb = (sender as MyRitchTextBox);
        if (rtb != null)
        {
            this.toolTip1.Show("Hello!!!", rtb);
        }
    }

    void myRTB_MouseLeave(object sender, EventArgs e)
    {
        MyRitchTextBox rtb = (sender as MyRitchTextBox);
        if (rtb != null)
        {
            this.toolTip1.Hide(rtb);
        }
    }


    public class MyRitchTextBox : RichTextBox
    {
    }

}

#4


2  

This is not elegant, but you might be able to use the RichTextBox.GetCharIndexFromPosition method to return to you the index of the character that the mouse is currently over, and then use that index to figure out if it's over a link, hotspot, or any other special area. If it is, show your tooltip (and you'd probably want to pass the mouse coordinates into the tooltip's Show method, instead of just passing in the textbox, so that the tooltip can be positioned next to the link).

这并不优雅,但是您可以使用RichTextBox。GetCharIndexFromPosition方法将鼠标当前结束的字符的索引返回给您,然后使用该索引来判断它是否位于链接、热点或其他特殊区域。如果是,请显示您的工具提示(并且您可能希望将鼠标坐标传递到tooltip的show方法中,而不是仅仅传入文本框,这样工具提示就可以放置在链接的旁边)。

Example here: http://msdn.microsoft.com/en-us/library/system.windows.forms.richtextbox.getcharindexfromposition(VS.80).aspx

例子:http://msdn.microsoft.com/en-us/library/system.windows.forms.richtextbox.getcharindexfromposition(VS.80). aspx

#5


0  

Use:

使用:

ToolTip tip = new ToolTip();
private void richTextBox1_MouseMove(object sender, MouseEventArgs e)
{
    Cursor a = System.Windows.Forms.Cursor.Current;
    if (a == Cursors.Hand)
    {
        Point p = richTextBox1.Location;
        tip.Show(
            GetWord(richTextBox1.Text,
                richTextBox1.GetCharIndexFromPosition(e.Location)),
            this,
            p.X + e.X,
            p.Y + e.Y + 32,
            1000);
    }
}

Use the GetWord function from my other answer to get the hovered word. Use timer logic to disable reshow the tooltip as in prev. example.

从我的另一个答案中使用GetWord函数来得到这个盘旋的单词。使用定时器逻辑来禁用在prev中显示工具提示。的例子。

In this example right above, the tool tip shows the hovered word by checking the mouse pointer.

在上面的例子中,工具提示通过检查鼠标指针来显示这个盘旋的单词。

If this answer is still not what you are looking fo, please specify the condition that characterizes the word you want to use tooltip on. If you want it for bolded word, please tell me.

如果这个答案仍然不是您所看到的,请指定您想要使用工具提示的单词的特征。如果你想用粗话,请告诉我。

#6


0  

I would also like to add something here that if you load desired form that contain tooltip controll before the program's run then tool tip control on that form will not work as described below...

我还想在这里添加一些东西,如果你在程序运行之前加载了包含工具提示控制的表单,那么工具提示控件就不会像下面描述的那样工作了……

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        objfrmmain = new Frm_Main();
        Showtop();//this is procedure in program.cs to load an other form, so if that contain's tool tip control then it will not work
        Application.Run(objfrmmain);


    }

so I solved this problem by puting following code in Fram_main_load event procedure like this

因此,我通过在Fram_main_load事件过程中执行以下代码来解决这个问题。

    private void Frm_Main_Load(object sender, EventArgs e)
    {
        Program.Showtop();
    }

#7


0  

As there is nothing in this question (but its age) that requires a solution in Windows.Forms, here is a way to do this in WPF in code-behind.

由于这个问题(但它的年龄)没有任何问题,所以需要在Windows中解决问题。表单,这是在WPF中在代码后做这个的一种方法。

TextBlock tb = new TextBlock();
tb.Inlines.Add(new Run("Background indicates packet repeat status:"));
tb.Inlines.Add(new LineBreak());
tb.Inlines.Add(new LineBreak());
Run r = new Run("White");
r.Background = Brushes.White;
r.ToolTip = "This word has a White background";
tb.Inlines.Add(r);
tb.Inlines.Add(new Run("\t= Identical Packet received at this time."));
tb.Inlines.Add(new LineBreak());
r = new Run("SkyBlue");
r.ToolTip = "This word has a SkyBlue background";
r.Background = new SolidColorBrush(Colors.SkyBlue);
tb.Inlines.Add(r);
tb.Inlines.Add(new Run("\t= Original Packet received at this time."));

myControl.Content = tb;

#8


0  

If you are using RichTextBox control. You can simply define the ToolTip object and show the tool-tip as the text is selected by moving the mouse inside the RichTextBox control.

如果你使用的是RichTextBox控件。您可以简单地定义工具提示对象并显示工具提示,因为文本是通过在RichTextBox控件中移动鼠标来选择的。

    ToolTip m_ttInput = new ToolTip(); // define as member variable

    private void rtbInput_SelectionChanged(object sender, EventArgs e)
    {
        if (rtbInput.SelectedText.Length > 0) 
        {
            m_ttInput.Show(rtbInput.SelectedText.Length.ToString(), rtbInput, 1000);
        }
    }

#9


0  

For the sake of ease of use and understandability.

为了便于使用和理解。

You can simply put a Tooltip anywhere on your form (from toolbox). You will then be given an options in the Properties of everything else in your form to determine what is displayed in that Tooltip (it reads something like "ToolTip on toolTip1"). Anytime you hover on an object, the text in that property will be displayed as a tooltip.

您可以简单地将工具提示放在表单的任何地方(从工具箱)。然后,您将在表单的所有其他属性中得到一个选项,以确定该工具提示中显示的内容(它读到类似于“toolTip1”的“工具提示”)。当您在对象上停留时,该属性中的文本将显示为工具提示。

This does not cover custom on-the-fly tooltips like the original question is asking for. But I am leaving this here for others that do not need

这并不包括像原始问题所要求的那样的动态工具提示。但我把这个留给那些不需要的人。

#1


12  

Well, take a look, this works, If you have problems please tell me:

嗯,看一看,如果你有问题,请告诉我:

using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1() { InitializeComponent(); }

        ToolTip tip = new ToolTip();
        void richTextBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (!timer1.Enabled)
            {
                string link = GetWord(richTextBox1.Text, richTextBox1.GetCharIndexFromPosition(e.Location));
                //Checks whether the current word i a URL, change the regex to whatever you want, I found it on www.regexlib.com.
//you could also check if current word is bold, underlined etc. but I didn't dig into it.
                if (System.Text.RegularExpressions.Regex.IsMatch(link, @"^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*$"))
                {
                    tip.ToolTipTitle = link;
                    Point p = richTextBox1.Location;
                    tip.Show(link, this, p.X + e.X,
                        p.Y + e.Y + 32, //You can change it (the 35) to the tooltip's height - controls the tooltips position.
                        1000);
                    timer1.Enabled = true;
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e) //The timer is to control the tooltip, it shouldn't redraw on each mouse move.
        {
            timer1.Enabled = false;
        }

        public static string GetWord(string input, int position) //Extracts the whole word the mouse is currently focused on.
        {
            char s = input[position];
            int sp1 = 0, sp2 = input.Length;
            for (int i = position; i > 0; i--)
            {
                char ch = input[i];
                if (ch == ' ' || ch == '\n')
                {
                    sp1 = i;
                    break;
                }
            }

            for (int i = position; i < input.Length; i++)
            {
                char ch = input[i];
                if (ch == ' ' || ch == '\n')
                {
                    sp2 = i;
                    break;
                }
            }

            return input.Substring(sp1, sp2 - sp1).Replace("\n", "");
        }
    }
}

#2


9  

Just add ToolTip tool from toolbox to the form and add this code in a mousemove event of any control you want to make the tooltip start on its mousemove

只需将ToolTip工具从工具箱添加到表单,并将此代码添加到任何控件的mousemove事件中,您希望将工具提示从它的mousemove上启动。

private void textBox3_MouseMove(object sender, MouseEventArgs e)
    {
      toolTip1.SetToolTip(textBox3,"Tooltip text"); // you can change the first parameter (textbox3) on any control you wanna focus
    }

hope it helps

希望它能帮助

peace

和平

#3


4  

You shouldn't use the control private tooltip, but the form one. This example works well:

您不应该使用控件私有工具提示,而是使用表单。这个例子的作品:

public partial class Form1 : Form
{
    private System.Windows.Forms.ToolTip toolTip1;

    public Form1()
    {
        InitializeComponent();
        this.components = new System.ComponentModel.Container();
        this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);

        MyRitchTextBox myRTB = new MyRitchTextBox();
        this.Controls.Add(myRTB);

        myRTB.Location = new Point(10, 10);
        myRTB.MouseEnter += new EventHandler(myRTB_MouseEnter);
        myRTB.MouseLeave += new EventHandler(myRTB_MouseLeave);
    }


    void myRTB_MouseEnter(object sender, EventArgs e)
    {
        MyRitchTextBox rtb = (sender as MyRitchTextBox);
        if (rtb != null)
        {
            this.toolTip1.Show("Hello!!!", rtb);
        }
    }

    void myRTB_MouseLeave(object sender, EventArgs e)
    {
        MyRitchTextBox rtb = (sender as MyRitchTextBox);
        if (rtb != null)
        {
            this.toolTip1.Hide(rtb);
        }
    }


    public class MyRitchTextBox : RichTextBox
    {
    }

}

#4


2  

This is not elegant, but you might be able to use the RichTextBox.GetCharIndexFromPosition method to return to you the index of the character that the mouse is currently over, and then use that index to figure out if it's over a link, hotspot, or any other special area. If it is, show your tooltip (and you'd probably want to pass the mouse coordinates into the tooltip's Show method, instead of just passing in the textbox, so that the tooltip can be positioned next to the link).

这并不优雅,但是您可以使用RichTextBox。GetCharIndexFromPosition方法将鼠标当前结束的字符的索引返回给您,然后使用该索引来判断它是否位于链接、热点或其他特殊区域。如果是,请显示您的工具提示(并且您可能希望将鼠标坐标传递到tooltip的show方法中,而不是仅仅传入文本框,这样工具提示就可以放置在链接的旁边)。

Example here: http://msdn.microsoft.com/en-us/library/system.windows.forms.richtextbox.getcharindexfromposition(VS.80).aspx

例子:http://msdn.microsoft.com/en-us/library/system.windows.forms.richtextbox.getcharindexfromposition(VS.80). aspx

#5


0  

Use:

使用:

ToolTip tip = new ToolTip();
private void richTextBox1_MouseMove(object sender, MouseEventArgs e)
{
    Cursor a = System.Windows.Forms.Cursor.Current;
    if (a == Cursors.Hand)
    {
        Point p = richTextBox1.Location;
        tip.Show(
            GetWord(richTextBox1.Text,
                richTextBox1.GetCharIndexFromPosition(e.Location)),
            this,
            p.X + e.X,
            p.Y + e.Y + 32,
            1000);
    }
}

Use the GetWord function from my other answer to get the hovered word. Use timer logic to disable reshow the tooltip as in prev. example.

从我的另一个答案中使用GetWord函数来得到这个盘旋的单词。使用定时器逻辑来禁用在prev中显示工具提示。的例子。

In this example right above, the tool tip shows the hovered word by checking the mouse pointer.

在上面的例子中,工具提示通过检查鼠标指针来显示这个盘旋的单词。

If this answer is still not what you are looking fo, please specify the condition that characterizes the word you want to use tooltip on. If you want it for bolded word, please tell me.

如果这个答案仍然不是您所看到的,请指定您想要使用工具提示的单词的特征。如果你想用粗话,请告诉我。

#6


0  

I would also like to add something here that if you load desired form that contain tooltip controll before the program's run then tool tip control on that form will not work as described below...

我还想在这里添加一些东西,如果你在程序运行之前加载了包含工具提示控制的表单,那么工具提示控件就不会像下面描述的那样工作了……

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        objfrmmain = new Frm_Main();
        Showtop();//this is procedure in program.cs to load an other form, so if that contain's tool tip control then it will not work
        Application.Run(objfrmmain);


    }

so I solved this problem by puting following code in Fram_main_load event procedure like this

因此,我通过在Fram_main_load事件过程中执行以下代码来解决这个问题。

    private void Frm_Main_Load(object sender, EventArgs e)
    {
        Program.Showtop();
    }

#7


0  

As there is nothing in this question (but its age) that requires a solution in Windows.Forms, here is a way to do this in WPF in code-behind.

由于这个问题(但它的年龄)没有任何问题,所以需要在Windows中解决问题。表单,这是在WPF中在代码后做这个的一种方法。

TextBlock tb = new TextBlock();
tb.Inlines.Add(new Run("Background indicates packet repeat status:"));
tb.Inlines.Add(new LineBreak());
tb.Inlines.Add(new LineBreak());
Run r = new Run("White");
r.Background = Brushes.White;
r.ToolTip = "This word has a White background";
tb.Inlines.Add(r);
tb.Inlines.Add(new Run("\t= Identical Packet received at this time."));
tb.Inlines.Add(new LineBreak());
r = new Run("SkyBlue");
r.ToolTip = "This word has a SkyBlue background";
r.Background = new SolidColorBrush(Colors.SkyBlue);
tb.Inlines.Add(r);
tb.Inlines.Add(new Run("\t= Original Packet received at this time."));

myControl.Content = tb;

#8


0  

If you are using RichTextBox control. You can simply define the ToolTip object and show the tool-tip as the text is selected by moving the mouse inside the RichTextBox control.

如果你使用的是RichTextBox控件。您可以简单地定义工具提示对象并显示工具提示,因为文本是通过在RichTextBox控件中移动鼠标来选择的。

    ToolTip m_ttInput = new ToolTip(); // define as member variable

    private void rtbInput_SelectionChanged(object sender, EventArgs e)
    {
        if (rtbInput.SelectedText.Length > 0) 
        {
            m_ttInput.Show(rtbInput.SelectedText.Length.ToString(), rtbInput, 1000);
        }
    }

#9


0  

For the sake of ease of use and understandability.

为了便于使用和理解。

You can simply put a Tooltip anywhere on your form (from toolbox). You will then be given an options in the Properties of everything else in your form to determine what is displayed in that Tooltip (it reads something like "ToolTip on toolTip1"). Anytime you hover on an object, the text in that property will be displayed as a tooltip.

您可以简单地将工具提示放在表单的任何地方(从工具箱)。然后,您将在表单的所有其他属性中得到一个选项,以确定该工具提示中显示的内容(它读到类似于“toolTip1”的“工具提示”)。当您在对象上停留时,该属性中的文本将显示为工具提示。

This does not cover custom on-the-fly tooltips like the original question is asking for. But I am leaving this here for others that do not need

这并不包括像原始问题所要求的那样的动态工具提示。但我把这个留给那些不需要的人。