Multi select ctrl + button pressed at runtime

In my winform, I have usercontrols that are created dynamically every time a button is clicked. I want them to be able to select them at runtime simply by clicking on them once and then pressing the ctrl button. I managed to do this, but only for one. How can I make it work for everyone? My code is:

  private void TControl_Click(object sender, EventArgs e) //TControl is the name of usercontrol
    {
        TControl tc = new TControl();
        Control ctrl = sender as Control;
        if (ctrl != null)
       tc = ctrl;//it doesn't work like this.
+5
source share
1 answer

You may have a list of selected controls. Just determine if Ctrl was pressed when you clicked on the control and added it to the selected list (you can also delete it if the control was previously added):

List<TControl> selectedControls = new List<TControl>();

private void TControl_Click(object sender, EventArgs e)
{
    if ((ModifierKeys & Keys.Control) == 0)
        return;

    TControl tc = (TControl)sender;
    if (selectedControls.Contains(tc))
        return; // you can remove control here

    selectedControls.Add(tc);
}
+2
source

All Articles