0

xaml file

PreviewKeyDown="Window_KeyDown"

.cs file

private void Window_KeyDown(object sender, KeyEventArgs e)
{
    System.Windows.Forms.MessageBox.Show(e.Key.ToString());
    if (e.Key == Key.Escape)
    {
        this.Close();
    }
}

KeyPreview is set to true, although the message box doesn't appear for the ESC key. (the message box does show for other "normal" keys such as 0-9 and a-z). How would I fix this or find a way to trigger something on ESC?


EDIT


Win.xaml

<Window x:Class="WindowsFormsApplication5.Win"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         WindowStyle="None" 
         PreviewKeyDown="Window_KeyDown">
</Window>

Win.xaml.cs

public partial class Win : Window
{
    public Win()
    {
        InitializeComponent();
    }

    private void Window_KeyDown(object sender, KeyEventArgs e)
    {
        System.Windows.MessageBox.Show(e.Key.ToString());
        if (e.Key == Key.Escape)
        {
            this.Close();
        }
    }
}

Form1.cs

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Win scrn = new Win();
        scrn.Show();
    }
}

Hopefully this should clear up any issues, sorry for being unclear about this.

user1768788
  • 1,265
  • 1
  • 10
  • 29

2 Answers2

0

Maybe WPF MessageBox is relevant

This works just fine for me

<Window PreviewKeyDown="wPreviewKeyDown"

private void wPreviewKeyDown(object sender, KeyEventArgs e)
{
    MessageBox.Show(e.Key.ToString());
    if (e.Key == Key.Escape)
        this.Close();
}

Do you have another control that is possibly handling the event?

paparazzo
  • 44,497
  • 23
  • 105
  • 176
0

In case you are running the WPF dialog from within a WinForms form, the Escape key appears to be filtered out. Here is a fix:

var wpfWindow = new SomeWpfWindow();
ElementHost.EnableModelessKeyboardInterop(wpfWindow);
wpfWindow.Show();
Dimitri C.
  • 21,861
  • 21
  • 85
  • 101