Search code examples
c#eventtrigger

C# how to trigger MouseMove or MouseEnter events if MouseButton is down when entering a control?


I need to trigger MouseMove or MouseEnter event, while Mouse LeftButton is down. Unfortunately while the Mouse LeftButton is down, those events are not triggered.

I already tried the solution in this thread : C# triggering MouseEnter even even if mouse button is held down

But it doesnt work because it's working on the Form only and not the controls. The idea is simple, let's say I have 10 labels next to each others. After I MouseDown on one label --> its background color change to red, and then I keep the MouseLeftButton down and keep moving the mouse to other labels, I would like those labels backcolor to also change to red, without having releasing the mouse at any point.

I tried to use a boolean variable to store the state of the mouse button, at MouseDown event --> MouseDown = true; Then use that boolean at MouseEnter, or MouseMove, but those events are simply not triggered. Thanks all.


Solution

  • Must be in the MouseDown event use Label.Capture = false; that this event to allow other events to run .

    I put the complete code

    public partial class Form1 : Form
    {
       bool Ispressed = false; 
       public Form1()
       {
          InitializeComponent();
          for(int i=1; i<=10;i++)
          {
              Label lbl = new Label();
              lbl.Name = "lbl" + i;
              lbl.Text = "Label " + i;
              lbl.Location = new System.Drawing.Point(150, i * 40);
              lbl.MouseDown += new MouseEventHandler(Lbl_MouseDown);
              lbl.MouseUp += new MouseEventHandler(Lbl_MouseUp);
              lbl.MouseMove += new MouseEventHandler(Lbl_MouseMove);
              lbl.MouseLeave += new System.EventHandler(Lbl_MouseLeave);
              this.Controls.Add(lbl);
          }
       }
       private void Lbl_MouseMove(object sender, MouseEventArgs e)
       {
          if (Ispressed)
          {
              Label lbl = sender as Label;
              lbl.BackColor = Color.Red;
          }
       }
    
       private void Lbl_MouseLeave(object sender, EventArgs e)
       {
          Label lbl = sender as Label;
          lbl.BackColor = Color.Transparent;
       }       
       private void Lbl_MouseDown(object sender, MouseEventArgs e)
       {
          Label lbl = sender as Label;
          lbl.BackColor = Color.Red;
    
          lbl.Capture = false;
          Ispressed = true;
       }
       private void Lbl_MouseUp(object sender, MouseEventArgs e)
       {
           Ispressed = false;
           foreach(Control ctr in this.Controls)
           {
              if(ctr is Label)
              {
                 ctr.BackColor = Color.Transparent;
              }
           }
       }
     }