-2

I have a ListView with the following KeyDown event handler:

private void ListViewOnKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.A)
    {
        Debug.WriteLine("KeyDown is A");
        if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
        {
            ListViewHelper.SelectAll((ListView)sender);
        }
    }
}

Yet the Debug.WriteLine is only ever invoked, i.e. I see KeyDown is A in my output window, if I only press key A. If I press CTRL, the event is invoked, but e.Key shows as LeftCtrl (using a breakpoint), and hold CTRL down and press A, the Debug.WriteLine is not invoked. Using a breakpoint for debugging shows that while I am holding CTRL down, the handler keeps getting invoked for LeftCtrl only.

ProfK
  • 49,207
  • 121
  • 399
  • 775
  • Can someone please explain the down-vote? I have found numerous search results showing that this is how to detect such a key-press combination, yet it is not working as expected. I would also like to know how the question was voted down the instant it was posted? Is there some little minded bureaucrat that sits waiting for questions to potentially vote down? – ProfK Jun 17 '18 at 10:09
  • Can someome also please explain how in the name of all that is right, a question tagged WPF et al. is asking exactly why code that I wrote that relates to all the tags, can rightly be voted to close as "off-topic"? – ProfK Jun 17 '18 at 10:45

1 Answers1

1

It's not working because the special combination is already handled by ListBox control.

Using PreviewKeyDown instead seems to work. Pay attention by setting e.Handled = true;

Liuk
  • 111
  • 7
  • It's not a `ListBox` but a `ListView`, quite different controls, and that key combination does nothing when I try and use it to select all items in the `ListView`. – ProfK Jun 17 '18 at 19:09
  • @ProfK Quite different controls? ListView is derived from ListBox, and PreviewKeyDown just works. You didn't even try it, right? – Clemens Jun 17 '18 at 20:04
  • 1
    @ProfK I'm sorry for the mistake, it should work the same way with ListView too. – Liuk Jun 17 '18 at 22:30
  • @Clemens For my WPF knowledge and the way I use them, they are quite different. `PreviewKeyDown` has nothing do do with your comment, as I was referring to `ListView` not responding to CTRL+A, not saying `PreviewKeyDown` doesn't work before trying it. My comment was made at end of day yesterday, and at the same time I made a note to try `PreviewKeyDown`. But thanks for the info that on how the controls are related. – ProfK Jun 18 '18 at 05:00
  • @Liuk It is not a mistake to say that the key combination is already handled by the ListBox class, because it is the base class of ListView. Hence the key combination is implicitly also handled by a ListView. – Clemens Jun 18 '18 at 05:11