Bra*_*Dev 22 c# tooltip picturebox
好的,我是一个完全的初学者,并设法在C#中组合一个小应用程序,我在文本框中输入用户名,应用程序获取该用户名的头像并将其显示在图片框中.
我想要做的是让工具提示显示鼠标悬停在加载的头像上时在文本框中键入的用户名.它应该在每次加载新头像时更改.我知道如何以正常方式使用工具提示,但这对我来说有点复杂.任何帮助将不胜感激.
谢谢.
Joe*_*Joe 39
使用以下代码将悬停事件添加到您的图片框中.
private void pictureBox1_MouseHover(object sender, EventArgs e)
{
ToolTip tt = new ToolTip();
tt.SetToolTip(this.pictureBox1, "Your username");
}
Run Code Online (Sandbox Code Playgroud)
Bra*_*ler 19
乔斯的答案确实完成了工作,但效率很低.ToolTip每次PictureBox悬停时代码都会创建一个新代码.使用该SetToolTip()方法时,它会将创建的内容ToolTip与指定的控件相关联,并保留ToolTip内存.您只需要调用此方法一次.我建议你在表单构造函数中只ToolTip为每个创建一个PictureBox.我已经测试了这个并且工作正常,工具提示对我来说更快:
public MyForm()
{
InitializeComponent();
// The ToolTip for the PictureBox.
new ToolTip().SetToolTip(pictureBox1, "The desired tool-tip text.");
}
Run Code Online (Sandbox Code Playgroud)
小智 6
Brandon-Miller 的回答很好,只是他建议为每个图片框创建一个工具提示。这仍然是无效的,虽然比 Joe 的方法更好 - 因为对于整个表单,您实际上并不需要一个以上的 Tooltip 对象!它可以为不同的控件(表单上的点点滴滴)创建数以千计的“工具提示定义”(可能不是实际术语)。这就是为什么在创建或设置工具提示时将控件定义为第一个参数的原因。
据我所知,正确(或至少是最不浪费的)方法是为每个表单创建一个 Tooltip 对象,然后使用SetTooltip函数为不同的控件创建“定义”。
例子:
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");
}
Run Code Online (Sandbox Code Playgroud)
或者,稍有不同,预先完成初始化:
// 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");
}
Run Code Online (Sandbox Code Playgroud)
如果在窗体设计器中添加了工具提示,则可以省略开头的声明。您甚至不需要对其进行初始化(据我所知,这应该由设计器生成的代码来完成),只需使用 SetToolTip 为不同的控件创建新的工具提示即可。