1 year ago

#382888

test-img

Dalibor

Windows Forms - How do I select all items in Listbox by pressing Ctrl A

In Windows Forms, I want user to be able to select all items in a Listbox by pressing default hotkeys as we are all used to, Ctrl + A.

I came up with something like this, and although it works,

    private bool clickedControl;
    private void lstFiles_KeyUp(object sender, KeyEventArgs e)
    {
        // reset clicked ctrl:
        clickedControl = false;
    }

    private void lstFiles_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyValue == 17)
        {
            clickedControl = true;
        }
        else
        {
            if (clickedControl == true && e.KeyValue == 65)
            {
                // clicked Ctrl + A, select all items:
                for (int i = 0; i < lstFiles.Items.Count; i++)
                {
                    lstFiles.SetSelected(i, true);
                }
            }
        }
    }

this feels so very wrong and boilerplated, and I needed to introduce flag clickedControl, and I could be missing something that I haven't noticed, so I'm sure WinForms and .NET 4x has some better solution for my problem?

c#

.net

winforms

listbox

0 Answers

Your Answer

Accepted video resources