Moving Object with Paint Event

若如初见. 提交于 2019-12-10 23:38:40

问题


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


回答1:


I found it!

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




回答2:


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.



来源:https://stackoverflow.com/questions/18602531/moving-object-with-paint-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!