Key press in c sharp. What am I doing wrong?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • guest087123
    New Member
    • Feb 2010
    • 5

    #1

    Key press in c sharp. What am I doing wrong?

    I'm pretty new to c sharp... can't get this going. When the user presses z move my animation. This is what I have coded but nothing happens. What am I doing wrong.

    Code:
    private void Form1_KeyPress(object sender, KeyPressEventArgs e)
    {         
                switch (e.KeyChar) 
                {
                    case 'Z':
                        tank1.TurnBarrelLeft();
                        break;
                    case 'X':
                        tank1.TurnBarrelRight();
                        break;
                }
    }.
    Last edited by tlhintoq; Feb 12 '10, 05:06 PM. Reason: [CODE] ...Your code goes between code tags [/CODE]
  • Curtis Rutland
    Recognized Expert Specialist
    • Apr 2008
    • 3264

    #2
    Well, I would use the KeyDown event, first of all.

    Did you assign this method to the event handler, or did you just type/paste it in? What I mean is, did you use the Properties panel on the form editor to add the handler?

    If you did, you should put a breakpoint in at your method, and see if it's actually being called.

    Anyway, here's how I would handle it myself, to remove ambiguity:
    Code:
    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        switch (e.KeyCode)
        {
            case Keys.Z:
                //whatever;
                break;
            case Keys.X:
                //whatever;
                break;
            default:
                //sanity check
                break;
        }
    }

    Comment

    • tlhintoq
      Recognized Expert Specialist
      • Mar 2008
      • 3532

      #3
      TIP: When you are writing your question, there is a button on the tool bar that wraps the [code] tags around your copy/pasted code. It helps a bunch. Its the button with a '#' on it. More on tags. They're cool. Check'em out.

      Comment

      • guest087123
        New Member
        • Feb 2010
        • 5

        #4
        I used a breakpoint and found out it wasn't executing. I was overriding the ProccessCmdKey method ( I thought this was just used for arrow keys ) , so I just popped the code in there and it worked. Thanks for the help

        Comment

        • Curtis Rutland
          Recognized Expert Specialist
          • Apr 2008
          • 3264

          #5
          Glad to be of service.

          Comment

          Working...