Tooltips for CheckedListBox items?

后端 未结 5 743
盖世英雄少女心
盖世英雄少女心 2021-01-17 10:20

Is there a straighforward way to set additional text to appear in a tooltip when a user\'s mouse is held over an item in a CheckedListBox?

What I would expect

5条回答
  •  Happy的楠姐
    2021-01-17 10:31

    I would like to expand upon Fermin's answer in order to perhaps make his wonderful solution slightly more clear.

    In the form that you're working in (likely in the .Designer.cs file), you need to add a MouseMove event handler to your CheckedListBox (Fermin originally suggested a MouseHover event handler, but this did not work for me).

    this.checkedListBox.MouseMove += new System.Windows.Forms.MouseEventHandler(this.showCheckBoxToolTip);
    

    Next, add two class attributes to your form, a ToolTip object and an integer to keep track of the last checkbox whose tool tip was shown

    private ToolTip toolTip1;
    private int toolTipIndex;
    

    Finally, you need to implement the showCheckBoxToolTip() method. This method is very similar to Fermin's answer, except that I combined the event callback method with the ShowToolTip() method. Also, notice that one of the method parameters is a MouseEventArgs. This is because the MouseMove attribute requires a MouseEventHandler, which then supplies MouseEventArgs.

    private void showCheckBoxToolTip(object sender, MouseEventArgs e)
    {
        if (toolTipIndex != this.checkedListBox.IndexFromPoint(e.Location))
        {
            toolTipIndex = checkedListBox.IndexFromPoint(checkedListBox.PointToClient(MousePosition));
            if (toolTipIndex > -1)
            {
                toolTip1.SetToolTip(checkedListBox, checkedListBox.Items[toolTipIndex].ToString());
            }
        }
    }
    

提交回复
热议问题