问题
My WPF application has behaviour triggered by the functions keys (F1-F12).
My code is along these lines:
private void Window_KeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.F1:
...
case Key.F2:
...
}
}
This works for all F-keys except F10. Debugging, I find that e.Key == Key.System
when the user presses F10.
In the enum definition, F10 = 99
and System = 156
, so I can rule out it being a duplicate enum value (like PageDown = Next = 20
).
So, how do I tell when the user presses F10?
Is it safe to check for Key.System
instead? This feels a little dirty - might it be possible that Key.System
would ever result from some other key being pressed? Or is there some setting somewhere that will make F10 report as Key.F10
?
回答1:
In addition to Yacoder's response, use the following to check for the F10 key:
case Key.System:
if (e.SystemKey == Key.F10)
{
// logic...
}
The SystemKey property will tell you which System key was pressed.
回答2:
F10 launches the window menu. It's the same in all Windows apps.
It seems that Key.System
is the expected value for the F10 key.
回答3:
Answer with DataContext:
public partial class BankView : UserControl
{
public BankView()
{
InitializeComponent();
this.KeyDown += new KeyEventHandler(BankView_KeyDown);
}
private void BankView_KeyDown(object sender, KeyEventArgs e)
{
try
{
switch (e.Key)
{
case Key.F4:
((BankViewModel)DataContext).OpenAccount();
break;
}
}
catch (Exception ex)
{
...
}
}
回答4:
This worked for me, for F1
Private Sub Window_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
If (e.Key = Key.F1) Then
ShowHelp()
End If
End Sub
来源:https://stackoverflow.com/questions/2103497/detecting-the-user-pressing-f10-in-wpf