将表单显示为工具提示

时间:2015-05-05 11:56:27

标签: c# winforms

我需要将Form显示为ToolTip的{​​{1}}。当鼠标位于UserControl上方时,必须显示UserControl,当鼠标离开Form时,UserControl必须隐藏。

我已经在我的UserControl类中覆盖了这些事件:

Form

没有例外,但不会调用事件。

2 个答案:

答案 0 :(得分:2)

显示表单将窃取焦点,它将被激活。因此,将Form显示为ToolTip并不是一个好主意。它不会像人们期望的那样表现。

您需要将ToolStripDropDownToolStripControlHost结合使用。这使得可以将任何控件显示为工具提示(不完全是这样)。

public partial class MainForm : Form
{
    private ToolStripDropDown dropDown = new ToolStripDropDown();
    public MainForm()
    {
        InitializeComponent();

        dropDown.Items.Add(new ToolStripControlHost(new ToolTipUserControl() { Size = new Size(200, 200) }));
    }

    protected override void OnMouseEnter(EventArgs e)
    {
        base.OnMouseEnter(e);
        dropDown.Show(MousePosition);
    }

    protected override void OnMouseLeave(EventArgs e)
    {
        base.OnMouseLeave(e);
        dropDown.Hide();
    }
}

ToolTipUserControl可以是您要显示为工具提示的任何Control

答案 1 :(得分:1)

以下是可能有用的代码示例:

private void ToolTipControl_Load(object sender, EventArgs e)
    {
        AttachHandlers(this);
    }

    private void AttachHandlers(Control currentControl)
    {
        foreach (Control control in currentControl.Controls)
        {
            control.MouseHover += GenericMouseHover;
            control.MouseLeave += GenericMouseLeave;

            if (control.Controls.Count != 0)
            {
                AttachHandlers(control);
            }
        }
    }

    void GenericMouseLeave(object sender, EventArgs e)
    {
        // no need to hide it if there was no form created in first place
        if(_form != null && _form.Visible)
        Form.Hide();
    }

    private void GenericMouseHover(object sender, EventArgs e)
    {
        Form.Location = this.PointToClient(Cursor.Position);
        Form.Show();
    }

    ToolTipForm _form;
    private ToolTipForm Form
    {
        get
        {
            if (_form == null)
            {
                _form = new ToolTipForm();
            }
            return _form;
        }
    }