[英]how to make a label go bold when a mouse go over it and back to normal afterwards
我正在尝试制作一个标签,该标签被动态更改为粗体,没有任何运气。
Use Control.MouseEnter and Control.MouseLeave and change the sender
's properties in the event handler: 使用Control.MouseEnter和Control.MouseLeave并在事件处理程序中更改
sender
的属性:
private void label1_MouseEnter(object sender, EventArgs e)
{
var font = ((Label)sender).Font;
((Label)sender).Font = new Font(font, FontStyle.Bold);
font.Dispose();
}
private void label1_MouseLeave(object sender, EventArgs e)
{
var font = ((Label)sender).Font;
((Label)sender).Font = new Font(font, FontStyle.Regular);
font.Dispose();
}
While there is nothing technically wrong with the currently accepted answer, I wanted to provide a slightly different alternative that I think makes it a lot easier to manage and keep track of what is going on here. 尽管当前接受的答案在技术上没有任何问题,但我想提供一个略有不同的替代方法,我认为它可以更轻松地管理和跟踪此处发生的情况。
This approach stores off two local copies of the Font (one bold, one normal). 此方法存储了Font的两个本地副本(一个粗体,一个普通)。 Then, you can just swap out the Font references in your mouse events and you only need to worry about disposing of the Fonts when you dispose of your parent class (or when you change the font).
然后,您可以在鼠标事件中交换出Font引用,并且只需要担心在处置父类(或更改字体)时就处置Fonts。
Also, this adds some error handling that people often forget when dealing with Fonts and Mouse events (namely try-catch the Font creation because it can fail and unregistering the mouse event handlers when disposing. 此外,这还会增加一些错误处理,人们在处理字体和鼠标事件时常常会忘记这些错误处理(即,尝试捕获字体创建,因为它可能会失败并在处理时取消注册鼠标事件处理程序。
public class MyClass
{
Font _normalFont;
Font _boldFont;
public MyClass() : IDisposble
{
try
{
_normalFont = new Font("Arial", 9);
_boldFont = new Font("Arial", 9, FontStyle.Bold);
}
catch
{
//error handling
}
label1.MouseEnter += label1_MouseEnter;
label1.MouseLeave += label1_MouseLeave;
}
private void label1_MouseEnter(object sender, EventArgs e)
{
var font = ((Label)sender).Font;
((Label)sender).Font = new Font(font, FontStyle.Bold);
font.Dispose();
}
private void label1_MouseLeave(object sender, EventArgs e)
{
var font = ((Label)sender).Font;
((Label)sender).Font = new Font(font, FontStyle.Regular);
font.Dispose();
}
public void Dispose()
{
label1.MouseEnter -= label1_MouseEnter;
label1.MouseLeave -= label1_MouseLeave;
if(_normalFont != null)
{
_normalFont.Dispose();
}
if(_boldFont != null)
{
_boldFont.Dispose();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.