Search code examples
.netwpfdialogkeyboardmodal-dialog

How to ignore Enter key from WPF modal dialog, in PreviewKeyUp


I have a WPF application. On it's main window it has a PreviewKeyUp handler, to handle certain global key presses - in this case, Enter. I've found when a modal dialog is showing (ShowDialog) and enter key is pressed, the enter goes to the PreviewKeyUp handler on the main window. Depending on your perspective, this may or may not make sense ... but it's definitely not what I want here.

So I can't see any way to intercept the Enter key reliably on the main window (regardless of focussed control), without also being called when Enter is pressed in a modal dialog.

This seems to be behaviour specific to the Enter key - it doesn't happen for other keys, such as digits.

Anyone got any ideas?

Main window code:

private void Window_PreviewKeyUp(object sender, KeyEventArgs e)
{
  switch (e.Key)
  {
    case Key.Enter:
      Controller.ProductSelected();
      ActionComplete();
      e.Handled = true;
      break;
  }
}


public bool PromptForPassword(string promptText, out string result)
{
  DataEntryForm entryForm = new DataEntryForm();
  entryForm.Owner = this;
  entryForm.PromptText = promptText;

  IsEnabled = false; // doesn't help
  entryForm.ShowDialog();
  IsEnabled = true;

  result = entryForm.EntryData;

  return (bool) entryForm.DialogResult;
}

Solution

  • In that situation I did this if it's of any use to you...

    Dispatcher.BeginInvoke(DispatcherPriority.Input, 
                (SendOrPostCallback)delegate { IsEnabled = false; }, new object[] { null }); 
    var dr = MessageBox.Show("Hello"); 
    Dispatcher.BeginInvoke(DispatcherPriority.Input, 
                (SendOrPostCallback)delegate { IsEnabled = true; }, new object[] { null }); 
    

    and the ENTER will be swallowed by the dialog box.