Change a label's forecolor on mouseovers

You can use the LinkLabel control in VB.NET but when it receives focus the focus rectangle is always drawn too small for my tastes. Instead, use the standard Label control and the following code:

    Imports System.Drawing;

    Private myFont As New Font("Microsoft Sans Serif", 8, FontStyle.Regular)
    Private myFontBold As New Font("Microsoft Sans Serif", 10, FontStyle.Bold)

    Private Sub LabelMouseEnter(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) _
            Handles Label1.MouseEnter, Label2.MouseEnter, Label3.MouseEnter
        '
        ' Set the font and forecolor when the cursor hovers over a label.
        '
        CType(sender, Label).ForeColor = System.Drawing.Color.Red
        CType(sender, Label).Font = myFontBold
    End Sub

    Private Sub LabelMouseLeave(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) _
            Handles Label1.MouseLeave, Label2.MouseLeave, Label3.MouseLeave
        '
        ' Reset the font and forecolor when the mouse stops hovering over a label.
        '
        CType(sender, Label).ForeColor = System.Drawing.Color.Blue
        CType(sender, Label).Font = myFont
    End Sub

Similarly, in C#:

    using System.Drawing;

    private Font myFont     = new Font("Microsoft Sans Serif", 8, FontStyle.Regular);
    private Font myFontBold = new Font("Microsoft Sans Serif", 10, FontStyle.Bold);

    private void LabelMouseEnter(object sender, System.EventArgs e)
    {
        //
        // Set the font and forecolor when the cursor hovers over a label.
        //
        Label lbl = (Label)sender;
        lbl.ForeColor = System.Drawing.Color.Red;
        lbl.Font = myLabelFontBig;
    }

    private void LabelMouseLeave(object sender, System.EventArgs e)
    {
        //
        // Reset the font and forecolor when the mouse stops hovering over a label.
        //
        Label lbl = (Label)sender;
        lbl.ForeColor = System.Drawing.Color.Blue;
        lbl.Font = myLabelFont;
    }




About TheScarms
About TheScarms


Sample code
version info

If you use this code, please mention "www.TheScarms.com"

Email this page


© Copyright 2024 TheScarms
Goto top of page