Click here to Skip to main content
15,910,234 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi i wanna use mouse enter and leave events for my user control.
i wanna changing user control forecolor when mouse enter,but don't work mouse enter event the user controls items,
my code user control is(this is for hover):
C#
private void lbl_operation_MouseHover(object sender, EventArgs e)
       {
           lbl_operation.ForeColor = Color.Yellow;
       }

how do i?
Posted

1 solution

Complete example for a UserControl:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Test_UserControl
{
    public partial class Form1 : Form
    {
        MyCtl ctl = new MyCtl();
        Color ctlDefaultColor;

        public Form1()
        {
            InitializeComponent();
            InitOthers();
        }

        private void InitOthers()
        {
            this.SuspendLayout();
            // set ctl properties
            this.ctl.Left = 10;
            this.ctl.Top = 10;
            this.Controls.Add(ctl);
            this.ctl.MouseEnter += ctl_MouseEnter;
            this.ctl.MouseLeave += ctl_MouseLeave;

            this.ctlDefaultColor = this.ctl.ForeColor;
            this.ResumeLayout(false);
            this.PerformLayout();
        }

        void ctl_MouseLeave(object sender, EventArgs e)
        {
            // restore backcolor
            this.ctl.ForeColor = this.ctlDefaultColor;
        }

        void ctl_MouseEnter(object sender, EventArgs e)
        {
            // set backcolor
            this.ctl.ForeColor = Color.Yellow;
        }
    }

    public class MyCtl : UserControl
    {
        Label lbl;
        Button btn;

        public MyCtl()
        {
            this.Initialize();
        }
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
        }
        private void Initialize()
        {
            this.SuspendLayout();
            this.lbl = new Label();
            this.lbl.Left = 10;
            this.lbl.Top = 10;
            this.lbl.Text = "There exists a label here";
            this.Controls.Add(this.lbl);

            this.btn = new Button();
            this.btn.Left = 10;
            this.btn.Top += this.lbl.Bottom + 10;
            this.btn.Text = "My Button";
            this.Controls.Add(this.btn);

            this.ResumeLayout(false);
        }
        
    }
}


And documentation: UserControl Class[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900