navigate in winforms by arrow keys

private void PositionCursor(object sender, PaintEventArgs e)
{
    Font arialBold = new Font("Arial", 14.0F);
    if (trigger)
    {
    TextRenderer.DrawText(e.Graphics, ("X"), arialBold,
         new Point(x * 20 - 4, y * 20 - 2), Color.Red);
        trigger = false;
    }
}
private void MoveCursor(object sender, KeyEventArgs e)
{
    switch (e.KeyCode)
    {
        case Keys.Up:
            y--;
            break;
        case Keys.Left:
            x--;
            break;
        case Keys.Down:
            x++;
            break;
        case Keys.Right:
            y++;
            break;
    }
    trigger = true;
}

Hello,

I'm trying to navigate a “X” on a winforms application by its x and y coordinates. I also tried the MoveCursor method with a ProcessCmdKey method instead of the KeyEventArgs. In both cases the switch operation does work fine, If I display the x and y values by a MessageBox the values change properly. But I don’t get the PaintEvent triggered when a Key is pressed, and I can’t find my thinking error. Please help me. Thanks!

Upvotes: 0

Views: 204

Answers (2)

lehiester
lehiester

Reputation: 900

As shared in this post, you should add a call to the form's Invalidate method at the end of MoveCursor:

private void MoveCursor(object sender, KeyEventArgs e)
{
    // ...
    trigger = true;
    this.Invalidate();
}

Upvotes: 0

When you call Invalidate on object in which cursor should update: ((Control)sender).Invalidate(), it should repaint after a moment. Probably at end of MoveCursor method.

You then have to hook PositionCursor to Paint event of that Control (which you maybe already did)

Upvotes: 0

Related Questions