加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 将按钮连接在一起

发布时间:2020-12-15 08:43:05 所属栏目:百科 来源:网络整理
导读:我试图在窗体上的某些按钮之间创建某种联系,这样当我单击一个按钮时,它会突出显示所有以前的按钮[某种音量控制器] 想象一下它是一个音量控制器.所有这些彩色按钮都是灰色的,我想要实现的是当你点击一个按钮时,它会将所有按钮着色;然而IDK在不涉及大量无用代
我试图在窗体上的某些按钮之间创建某种联系,这样当我单击一个按钮时,它会突出显示所有以前的按钮[某种音量控制器]

想象一下它是一个音量控制器.所有这些彩色按钮都是灰色的,我想要实现的是当你点击一个按钮时,它会将所有按钮着色;然而IDK在不涉及大量无用代码的情况下制作这样的行为的最佳方式是什么…

解决方法

首先,您需要将所有按钮添加到数组中,然后从那里处理它

//Create an array of buttons and hook up the Click event of each of them
private Button[] VolumeButtons { get; set; }

public Main()
{
    InitializeComponent();

    //Assuming that you have 21 buttons as it appears in your picture...
    VolumeButtons = new Button[21];
    VolumeButtons[0] = button1;
    VolumeButtons[1] = button2;
    VolumeButtons[2] = button3;
    VolumeButtons[3] = button4;
    VolumeButtons[4] = button5;
    VolumeButtons[5] = button6;
    VolumeButtons[6] = button7;
    VolumeButtons[7] = button8;
    VolumeButtons[8] = button9;
    VolumeButtons[9] = button10;
    VolumeButtons[10] = button11;
    VolumeButtons[11] = button12;
    VolumeButtons[12] = button13;
    VolumeButtons[13] = button14;
    VolumeButtons[14] = button15;
    VolumeButtons[15] = button16;
    VolumeButtons[16] = button17;
    VolumeButtons[17] = button18;
    VolumeButtons[18] = button19;
    VolumeButtons[19] = button20;
    VolumeButtons[20] = button21;

    foreach (var volumeButton in VolumeButtons)
        volumeButton.Click += VolumeButton_Click;
}

void VolumeButton_Click(object sender,EventArgs e)
{
    //Find the index of the clicked button
    int index = Array.FindIndex(VolumeButtons,VolumeButtons.Length,button => button == ((Button)sender));

    //Set the color of all the previous buttons to Aqua,and all the forward buttons to gray [ you may play with it to match your colors then ]
    for (int i = 0; i < VolumeButtons.Length; i++)
        VolumeButtons[i].BackColor = i <= index ? Color.Aqua : Color.Gray;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读