0

I'm trying to make a picture move whenever I press "a". I'm using this function:

void Form1_KeyPress(object sender, KeyPressEventArgs e) { if(e.KeyChar == 65) { peanut.Location = new System.Drawing.Point(0, 0); } } 

Above the function it says 0 references if that helps. Also "peanut" is the name of the picture box.

When using peanut.Location = new System.Drawing.Point(0, 0); when the form loads, it works. I think the problem has to do with getting the key input, not how I'm moving the picture.

I tried using the KeyPress function, but for some reason it isn't working. This might be because e.KeyChar 65 isn't A, but if it isn't, could somebody show me a list of all the values and keys associated with them?

1
  • I forgot to mention, I have already tried setting this.KeyPreview = true; in the Form1_Load function, and have now tried both those and checking if e.KeyChar == 97 too, still, nothing is working. Commented Nov 29, 2022 at 23:55

1 Answer 1

0

Try setting the Form's KeyPreview to true in the Form's load event, like this:

private void Form1_Load(object sender, EventArgs e) { this.KeyPreview = true; } 

Also if you want to move the picture box when the letter, a which has the value, 97 is pressed, try this:

void Form1_KeyPress(object sender, KeyPressEventArgs e) { if(e.KeyChar == 97) { peanut.Location = new System.Drawing.Point(0, 0); } } 
Sign up to request clarification or add additional context in comments.

4 Comments

Can you give me a list of all the numbers in keychar and their keys associated with them? If you didn't get it from a list and just learned some other way that's fine too.
@Catten The keychars values are taken from the ASCII values for the letters. Here is where I view the ASCII Values. Also if you wouldn't mind upvoting my answer :)
@Catten I recreated your code, and it ran perfectly for me, I can't think of anything else which would cause the errors you're getting.
Thanks, I found that it was just me forgetting I can't just create the function in my code, I have to have something reference it and now it is working, also thanks for the list of characters the list I was using was a little weird. Also, for anyone wondering, you have to "create an event" in the windows designer and then it will generate the function for you, you can't just write the function otherwise it will have no references and not work even if the code has no errors.