0

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?

Dalibor
  • 1,430
  • 18
  • 42
  • 1
    There are [easier](https://stackoverflow.com/a/1019443/1320845) [ways](https://stackoverflow.com/a/18376703/1320845) to check for Ctrl + A, but the general approach others have come up with is the same. – Charles Mager Apr 06 '22 at 14:42
  • Ah, I see `e.KeyCode == Keys.A && e.Control` I didn't know of the Control property. Thanks! – Dalibor Apr 06 '22 at 14:46

0 Answers0