c#如何触发MouseMove或MouseEnter事件,如果MouseButton在进入控件时按下?



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

我已经尝试了这个线程的解决方案:c#触发MouseEnter,即使按下鼠标按钮

但是它不起作用,因为它只作用于表单而不是控件。这个想法很简单,假设我有10个标签彼此相邻。在我按下一个标签之后——>它的背景色变为红色,然后我按住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;
}
}
}
}

最新更新