C# WPF键关闭未捕获逃逸?

C# WPF键关闭未捕获逃逸?,c#,wpf,keypress,keydown,C#,Wpf,Keypress,Keydown,xaml文件 PreviewKeyDown="Window_KeyDown" .cs文件 private void Window_KeyDown(object sender, KeyEventArgs e) { System.Windows.Forms.MessageBox.Show(e.Key.ToString()); if (e.Key == Key.Escape) { this.Close(); } } KeyPreview设置为true

xaml文件

PreviewKeyDown="Window_KeyDown"
.cs文件

private void Window_KeyDown(object sender, KeyEventArgs e)
{
    System.Windows.Forms.MessageBox.Show(e.Key.ToString());
    if (e.Key == Key.Escape)
    {
        this.Close();
    }
}
KeyPreview设置为true,但ESC键不会显示消息框。(对于其他“正常”键,如0-9和a-z,消息框中会显示)。我将如何解决这个问题或找到一种方法来触发ESC上的某些内容


编辑


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>
表格1.cs

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

    private void button1_Click(object sender, EventArgs e)
    {
        Win scrn = new Win();
        scrn.Show();
    }
}
希望这能解决所有问题,抱歉不清楚这一点。

也许WPF MessageBox是相关的

这对我来说很好

<Window PreviewKeyDown="wPreviewKeyDown"

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

如果您在WinForms窗体中运行WPF对话框,则转义键似乎已被过滤掉。这里有一个修正:

var wpfWindow = new SomeWpfWindow();
ElementHost.EnableModelessKeyboardInterop(wpfWindow);
wpfWindow.Show();

为什么要将Windows窗体
MessageBox
与WPF一起使用?重复的问题,已经在中得到了回答:我不知道,这是我所知道的显示弹出消息的最简单的方式,这真的相关吗?请改用
System.Windows.MessageBox
?您在哪里附加了
PreviewKeyDown
事件?去你的窗户?那么它应该会起作用;这对我来说确实有用。除非有另一个处理程序使用密钥事件并取消它。
var wpfWindow = new SomeWpfWindow();
ElementHost.EnableModelessKeyboardInterop(wpfWindow);
wpfWindow.Show();