obsługa klawaitury Windows Form

0

Witam. Mógł by mi ktoś powiedzieć gdzie jest błąd i dlaczego button nie zmienia swojego położenia po naciśnięciu danego klawisza?

oto kod:

public class Program
{

    static void Main()
    {
        MyForm t = new MyForm();
        Application.Run(t);

    }


}

public class MyForm : Form
{
    private Button but;
    public MyForm()
    {
        but = new Button();
        but.Location = new System.Drawing.Point(10, 10);
        this.Controls.Add(but);
        this.KeyDown += new KeyEventHandler(this.t_KeyDown);
    }
    
    public void t_KeyDown(object sender, KeyEventArgs e)
    {
        switch (e.KeyCode)
        {
            case Keys.Left:
                but.Location = new System.Drawing.Point(but.Location.X - 1, but.Location.Y);
            break;
            case Keys.Right:
                but.Location = new System.Drawing.Point(but.Location.X + 1, but.Location.Y);
            break;
            case Keys.Up:
                but.Location = new System.Drawing.Point(but.Location.X, but.Location.Y + 1);
            break;
            case Keys.Down:
                but.Location = new System.Drawing.Point(but.Location.X, but.Location.Y - 1);
            break;
            default:
            break;

        }
    }

aplikacja w ogóle nie reaguje na naciśnięte klawisze ;/
}

0

okej już wiem. pierwsza sprawa to nie można w ten sposób obsługiwać przycisków strzałek

Certain keys, such as the TAB, RETURN, ESCAPE, and arrow keys are handled by controls automatically. To have these keys raise the KeyDown event, you must override the IsInputKey method in each control on your form. The code for the override of the IsInputKey would need to determine if one of the special keys is pressed and return a value of true.

a druga to taka jesli zmieni sie strzałki na litery to trzeba jeszcze ustawić właściwośc KeyPreview dla formy na true.

pozdro

1 użytkowników online, w tym zalogowanych: 0, gości: 1