当我的鼠标指向c#中的按钮时,我想禁用其他按钮

本文关键字:按钮 其他 鼠标 我的 | 更新日期: 2023-09-27 18:06:06

当鼠标指向c#中的另一个按钮时,我想禁用其他按钮

 private void Form1_Load(object sender, EventArgs e){    
   foreach (Button btn in Controls.OfType<Button>())
   {
    btn.MouseEnter += new System.EventHandler(btn_MouseEnter);
    btn.MouseLeave += new System.EventHandler(btn_MouseLeave );
   }
}
private void btn_MouseEnter(object sender, System.EventArgs e) 
{
    var senderButton = (Button)sender;
    senderButton.Enable = true; // not working
}
private void btn_MouseLeave (object sender, System.EventArgs e) 
{
       var senderButton = (Button)sender;
       senderButton.Enable = false; // not working
}

当我的鼠标指向c#中的按钮时,我想禁用其他按钮

这可能不是最好的解决方案,但我还是要试试。

private void btn_MouseEnter(object sender, System.EventArgs e) 
{
    var senderButton = (Button)sender;
    foreach(var btn in this.Controls.OfType<Button>())
    {
        if (btn != senderButton)
            btn.Enabled = false;
    }
}
private void btn_MouseLeave(object sender, System.EventArgs e)
{
    foreach(var btn in this.Controls.OfType<Button>())
    {
        btn.Enabled = true;
    }
}

代替

senderButton.Enable = true;

你必须循环遍历所有按钮,比如

foreach(Button btn in this.Controls.OfType<Button>())
{
    if (btn != senderButton)
        btn.Enable = false; 
}
private void btn_MouseEnter(object sender, System.EventArgs e)
    {
        foreach (Button btn in Controls.OfType<Button>())
        {
            if (btn == ((Button)sender))
            {
                btn.Enabled = true; 
            }
            else
            {
                btn.Enabled = false;
            }
        }
    }
    private void btn_MouseLeave(object sender, System.EventArgs e)
    {
        foreach (Button btn in Controls.OfType<Button>())
        {
            btn.Enabled = true;
        }
    }