Moving Object with Paint Event

1.1k views Asked by At

I have a test tomorrow, and we must use the paint event to redraw our objects, we may not use a timer.

As the MSDN says: "The Paint event is raised when the control is redrawn.", but that,occurs for my known, only when the form is minimized, or got invisible and back visible.

My code:

public partial class Form1 : Form
{
    public Graphics drawArea;
    public int xPos, yPos;

    public Form1()
    {
        InitializeComponent();
    }
    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        drawArea = e.Graphics;
        DrawUser();
    }

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        switch (e.KeyCode)
        { 
            case Keys.Down:
                yPos++;
                break;
            case Keys.Up:
                yPos--;
                break;
            case Keys.Left:
                xPos--;
                break;
            case Keys.Right:
                xPos++;
                break;
        }
    }

    private void DrawUser()
    {
        drawArea.FillRectangle(new SolidBrush(Color.Red), xPos, yPos, 50, 50);
    }
}

So, When I press the key arrows multiple times, the object only moves after I re-size my form. I want it to move instantly, only using the paint event.

Thanks

2

There are 2 answers

4
crthompson On

It looks like you are tying up your form so it doesnt refresh until you move it. Try putting DoEvents after your drawArea in DrawUser

private void DrawUser()
{
    drawArea.FillRectangle(new SolidBrush(Color.Red), xPos, yPos, 50, 50);
    Application.DoEvents();
}

Be careful of DoEvents though, it can be evil.

1
Nick Peelman On

I found it!

By adding this.Invalidate(); after the key is pressed. This will tell the paint event to redraw.