Question

I am making a program with a panel on the User Control. I am trying to make it to be able to move. On the user control, I have set up a Key Down event handler, but that does not work. I am wondering if the problem is that that is not the control that has the focus? If not how could I ensure that it does? I have tried under my User Control (MainMap):

KeyDown +=  new KeyEventHandler(keyDown);

public void keyDown(object sender, KeyEventArgs e)
{
    switch (e.KeyData)
    {
        case Keys.Right:
            panel1.Location = new Point(panel1.Location.X + 5, panel1.Location.Y);
            Invalidate();
            break;
    }
}

Thanks

Était-ce utile?

La solution

You are almost there the sole problem is focus. However you can still achieve the same without focusing the control by using the PreviewKeyDown event so just change your code to use the same.

PreviewKeyDown += PreviewKeyDownHandler;

public void PreviewKeyDownHandler(object sender, PreviewKeyDownEventArgs e)
{
    switch (e.KeyData)
    {
        case Keys.Right:
            panel1.Location = new Point(panel1.Location.X + 5, panel1.Location.Y);
            Invalidate();
            break;
    }
}

this will work regardless of focus on the control.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top