我正在尝试在窗口(不是表单)中接收击键。我收到事件,直到按下按钮。之后,无论我做什么,按键事件都不再触发。有什么解决办法吗?我已经搜索过了,似乎每个人都在建议使用解决方案
this.KeyPreview = true;
但这在这里不起作用,因为 Window 没有这样的属性。非常感谢。我已经将所有的孩子 Focusable 设置为 False,并且 Window 设置为可聚焦。但这并没有帮助。
XAML 是
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="463" Width="726" AllowsTransparency="False" PreviewKeyDown="Window_PreviewKeyDown" KeyDown="Window_KeyDown_1" WindowStartupLocation="CenterScreen" Focusable="True">
<Window.Background>
<RadialGradientBrush>
<GradientStop Color="#FF3EB5FF" Offset="1" />
<GradientStop Color="White" Offset="0" />
</RadialGradientBrush>
</Window.Background>
<Grid Name="grid1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="434*" />
<ColumnDefinition Width="270*" />
</Grid.ColumnDefinitions>
<Grid Margin="10,10,0,12" Name="EquiGrid" Focusable="False">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="198*" />
</Grid.ColumnDefinitions>
<Image Grid.ColumnSpan="2" Name="EquiImage" Stretch="Uniform" Margin="0,0,0,6" />
<Grid Grid.Column="1" Height="100" HorizontalAlignment="Left" Margin="489,90,0,0" Name="grid2" VerticalAlignment="Top" Width="200" />
</Grid>
<Label Content="Label" Height="28" Margin="14,12,12,0" Name="longLabel" VerticalAlignment="Top" Grid.Column="1" OpacityMask="White" BorderBrush="Red" Focusable="False">
<Label.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="White" Offset="0.025" />
<GradientStop Color="#FFDBDBDB" Offset="1" />
</LinearGradientBrush>
</Label.Background>
</Label>
<Label Content="Label" Height="28" Margin="14,46,12,0" Name="latLabel" VerticalAlignment="Top" Grid.Column="1" Focusable="False">
<Label.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="White" Offset="0.025" />
<GradientStop Color="#FFDBDBDB" Offset="1" />
</LinearGradientBrush>
</Label.Background>
</Label>
<TextBlock Margin="14,80,12,54" Name="descriptionText" Padding="10" Text="" Grid.Column="1" Focusable="False"><TextBlock.Background><LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"><GradientStop Color="White" Offset="0.025" /><GradientStop Color="#FFDBDBDB" Offset="1" /></LinearGradientBrush></TextBlock.Background></TextBlock>
<Button Content="Load Image" Grid.Column="1" Margin="14,0,0,12" Name="button1" Height="36" VerticalAlignment="Bottom" HorizontalAlignment="Left" Width="124" Click="button1_Click" Focusable="False" />
<Button Content="Load XML" Grid.Column="1" Margin="0,0,12,12" Name="button2" Height="36" VerticalAlignment="Bottom" HorizontalAlignment="Right" Width="114" Click="button2_Click" Focusable="False" />
</Grid>
</Window>
和处理程序:
private void Window_KeyDown_1(object sender, System.Windows.Input.KeyEventArgs e)
{
Console.WriteLine("k");
}
我也发现问题出在焦点上。孩子们虽然设置为不可聚焦,但会窃取窗口上的焦点并停止事件触发。