Search code examples
c#wpflistboxkeypressrouted-events

How to disable key navigation in a ListBox but keep detect the key press events?


I'm trying to disable the key navigation in a ListBox. I can do it successfully with this code below :

private void listClips_PreviewKeyDown(object sender, KeyEventArgs e)
{
    e.Handled = true;
}

but I wanna add a keyboard shortcut for my program. It's not working when I set e.Handled = true.

private void listClips_KeyDown(object sender, KeyEventArgs e)
{
    MessageBox.Show("Key Pressed " + e.Key);
}

How can I keep both of them functional?


Solution

  • Can't you move your logic to the PreviewKeyDown handler?

    private void listClips_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        //custom logic...
        MessageBox.Show("Key Pressed " + e.Key);
    
        e.Handled = true;
    }
    

    Handle any shortcuts you want and always set the Handled property to true afterwards.