如果鼠标按钮在输入控件时按下,C# 如何触发 MouseMove 或 MouseEnter 事件?

问题描述

我需要在鼠标左键按下时触发 MouseMove 或 MouseEnter 事件。不幸的是,当鼠标左键按下时,这些事件不会被触发。

我已经在这个线程中尝试了解决方案: C# triggering MouseEnter even even if mouse button is held down

但它不起作用,因为它仅适用于表单而不适用于控件。 这个想法很简单,假设我有 10 个彼此相邻的标签。 在一个标签上的 MouseDown --> 其背景颜色更改为红色,然后我保持 MouseLeftButton 向下并将鼠标移动到其他标签后,我希望这些标签的背景颜色也更改为红色,而无需在以下位置释放鼠标任何一点。

我尝试在 MouseDown 事件中使用布尔变量来存储鼠标按钮的状态 --> MouseDown = true; 然后在 MouseEnter 或 MouseMove 处使用该布尔值,但这些事件根本不会被触发。 谢谢大家。

解决方法

必须在 MouseDown 事件中使用 Label.Capture = false; 表示此事件允许其他事件运行。

我放了完整的代码

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