我需要将Form
显示为ToolTip
的{{1}}。当鼠标位于UserControl
上方时,必须显示UserControl
,当鼠标离开Form
时,UserControl
必须隐藏。
我已经在我的UserControl类中覆盖了这些事件:
Form
没有例外,但不会调用事件。
答案 0 :(得分:2)
显示表单将窃取焦点,它将被激活。因此,将Form显示为ToolTip并不是一个好主意。它不会像人们期望的那样表现。
您需要将ToolStripDropDown与ToolStripControlHost结合使用。这使得可以将任何控件显示为工具提示(不完全是这样)。
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;
}
}