-3

I want a variable to be incremented when I press the spacebar. This is what I have tried so far, and it doesn't seem to be working. There's no error message, so I don't know what is wrong.

    public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
    int Coins = 0;
    int ButtonKeyNumber = (int)Key.Space;

    private void textBlockCoins_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
    {
        if (e.KeyValue == ButtonKeyNumber)
        {
            Coins = Coins + 1;
            textBlockCoins.Text = "You Have " + Coins + "Coins";
        }
    }
}

When I run the code, the textbox just says "You Have 0 Coins". The variable ButtonKeyNumber is there because I want to be able to easily change which key will need to be pressed.

  • Why do you need the variable at all? Compare directly to `Key.Space`, and then use the debugger to figure out what key you're getting in `e.KeyValue`. – Ken White Aug 19 '16 at 01:45
  • Is your KeyDown event callback actually being called? Make sure that the correct control has focus (first, click on textBlockCoins) to receive the KeyDown event. Put a breakpoint on the `if` and see what the value of e.KeyValue actually is! – khargoosh Aug 19 '16 at 01:46
  • did `textBlockCoins_KeyDown` trigger ? – Manu Varghese Aug 19 '16 at 01:48

2 Answers2

1

You might be using the wrong Keys class. Use the System.Windows.Forms.Keys class, this is the type that is provided by KeyEventArgs.KeyCode. Try something like this instead.

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
    int Coins = 0;
    Keys CoinKey = System.Windows.Forms.Keys.Space;

    private void textBlockCoins_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
    {
        if (e.KeyCode == CoinKey)
        {
            Coins = Coins + 1;
            textBlockCoins.Text = "You Have " + Coins + "Coins";
        }
    }
}

You still have to make sure the right control has focus when hitting the space key.

khargoosh
  • 1,450
  • 15
  • 40
0

Set KeyPreview to true on your form and you will catch them: MSDN

Original

Community
  • 1
  • 1
Ryan Peters
  • 180
  • 9