5

在我的 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.
4

1 回答 1

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);
}
于 2013-04-03T06:33:01.213 回答