KeyPress on entire form, not just one object?

I'm working on making pong in C#, and I've come across a problem. I have KeyPreview on, and here's my code

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
    if (e.KeyChar == (char)Keys.Up || e.KeyChar == (char)Keys.W) {
        picPaddle.Top -= 10;
    else if (e.KeyChar == (char)Keys.Down || e.KeyChar == (char)Keys.S) {
        picPaddle.Top += 10;

When I press any of the keys, nothing happens. The only time a keypress works is if it tests the condition for (char)Keys.Enter. Why is this? How can I make the form take KeyPress for keys other than enter?


Try overriding the KeyDown method instead:

protected override void OnKeyDown(KeyEventArgs e) {
  if (e.KeyCode == Keys.Up || e.KeyCode == Keys.W) {
    picPaddle.Top -= 10;
  } else if (e.KeyCode == Keys.Down || e.KeyCode == Keys.S) {
    picPaddle.Top += 10;


Also see What's the difference between KeyDown and KeyPress in .NET?

Need Your Help

NullReferenceException when reading an Array

c# arrays

The declaration of the Rectangle object fails with an NullReferenceException, maybe it has to do with the for loops (yMax and xMax are in tiles unit)

Test if Windows Hotfix is needed

windows windows-update hotfix

In a comment to Windows API equivalent to "WMIC QFE Get", Raymond Chen wrote that it is incorrect/useless to test if a hotfix is installed. The correct approach is to ask Windows Update i...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.