Nadav
Nadav

Reputation: 2717

how to make a label go bold when a mouse go over it and back to normal afterwards

I am trying to make a label which was made dynamically changed to a bold font without any luck.

Upvotes: 1

Views: 4350

Answers (2)

Tim
Tim

Reputation: 1874

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

Upvotes: 0

ulrichb
ulrichb

Reputation: 20054

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

Upvotes: 8

Related Questions