20

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?

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
teedyay
  • 23,293
  • 19
  • 66
  • 73

4 Answers4

21

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.

Gordon Bell
  • 13,337
  • 3
  • 45
  • 64
Will Eddins
  • 13,628
  • 5
  • 51
  • 85
  • That's cool. I find I also have to set `e.Handled = true` when `e.Key == Key.System`, to ensure the focus doesn't get left on the control box. (The control box is invisible in my app as I'm using `WindowStyle = None`, which makes the default F10 behaviour even more confusing for the user.) Also, `e.Key == Key.System` when the user presses the Alt key too - and maybe in some other cases - so `e.SystemKey` is definitely the way to go instead of just assuming it's F10. Thanks! – teedyay Jan 21 '10 at 10:08
4

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.

Massimiliano
  • 16,770
  • 10
  • 69
  • 112
1

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)
            {
                ...
            }
        }

RckLN
  • 4,272
  • 4
  • 30
  • 34
-2

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
Supun Wijerathne
  • 11,964
  • 10
  • 61
  • 87
kiev
  • 2,040
  • 9
  • 32
  • 54