多选ctrl +按钮在运行时单击

时间:2013-04-03 06:27:52

标签: c# winforms select user-controls

在我的winform上,我有每次点击按钮时动态创建的用户控件。我希望在运行时能够通过单击它们然后按下ctrl按钮来选择它们。我设法做到了,但只为一个。我怎样才能为所有人工作?我的代码:

  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.

1 个答案:

答案 0 :(得分:2)

您可以拥有所选控件的列表。只需确定单击控件时是否按下Ctrl并将其添加到选定列表(如果之前添加了控件,也可以将其删除):

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