好的,我是一名完全的初学者,并且成功地用C#编写了一个小应用程序,在文本框中输入用户名后,应用程序会获取该用户名的头像并在图片框中显示出来。
我想要做的是,当鼠标悬停在加载的头像上时,显示输入到文本框中的用户名。每次加载新的头像时,它都应该更改。我知道如何正常使用工具提示,但这对我来说有点复杂。任何帮助将不胜感激。
谢谢。
好的,我是一名完全的初学者,并且成功地用C#编写了一个小应用程序,在文本框中输入用户名后,应用程序会获取该用户名的头像并在图片框中显示出来。
我想要做的是,当鼠标悬停在加载的头像上时,显示输入到文本框中的用户名。每次加载新的头像时,它都应该更改。我知道如何正常使用工具提示,但这对我来说有点复杂。任何帮助将不胜感激。
谢谢。
使用以下代码为您的picturebox添加hover事件。
private void pictureBox1_MouseHover(object sender, EventArgs e)
{
ToolTip tt = new ToolTip();
tt.SetToolTip(this.pictureBox1, "Your username");
}
Joes的答案确实可以完成任务,但它效率低下。每次将鼠标悬停在PictureBox
上时,代码都会创建一个新的ToolTip
。当你使用SetToolTip()
方法时,它将创建的ToolTip
与指定的控件相关联并将其保留在内存中。你只需要调用一次这个方法。我建议你在窗体构造函数中为每个PictureBox
创建一个ToolTip
。我已经测试过了,它可以正常工作,并且对我来说工具提示显示得更快:
public MyForm()
{
InitializeComponent();
// The ToolTip for the PictureBox.
new ToolTip().SetToolTip(pictureBox1, "The desired tool-tip text.");
}
private ToolTip helperTip;
public MyForm()
{
InitializeComponent();
// The ToolTip initialization. Do this only once.
helperTip = new ToolTip(pictureBox1, "Tooltip text");
// Now you can create other 'definitions', still using the same tooltip!
helperTip.SetToolTip(loginTextBox, "Login textbox tooltip");
}
或者稍微不同,事先完成初始化:
// Instantiate a new ToolTip object. You only need one of these! And if
// you've added it through the designer (and renamed it there),
// you don't even need to do this declaration and creation bit!
private ToolTip helperTip = new ToolTip();
public MyForm()
{
InitializeComponent();
// The ToolTip setting. You can do this as many times as you want
helperTip.SetToolTip(pictureBox1, "Tooltip text");
// Now you can create other 'definitions', still using the same tooltip!
helperTip.SetToolTip(loginTextBox, "Login textbox tooltip");
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
ToolTip tooltip1 = new ToolTip();
tooltip1.Show(textBox1.Text, this.pictureBox1);
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
pictureBox1.Invalidate();
}
ToolTip
对象,然后在每次悬停事件时使用ToolTip.Show()
而不是创建一个新的提示框...? 另请参阅 此答案。 - Amos Egel