简体   繁体   中英

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:

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). 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).

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();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM