Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

c# - How to fix flicker in a WinForms form?

I am constantly drawing frames, and I need the form to not flicker. How do I accomplish this?

public partial class Form1 : Form
{
    Image[] dude = new Image[3];
    static int renderpoint = 0;
    int lastimage = 0;

    public Form1()
    {
        dude[1] = new Bitmap(@"snipe1.bmp");
        dude[0] = new Bitmap(@"snipe0.bmp");

        InitializeComponent();
    }

    private void Form1_Shown(object sender, EventArgs e)
    {
        MainLoop();
    }

    private void MainLoop()
    {
        double FPS = 10;

        long ticks1 = 0;
        long ticks2 = 0;
        double interval = (double)Stopwatch.Frequency / FPS;

        while (true)
        {
            ticks2 = Stopwatch.GetTimestamp();
            if (ticks2 >= ticks1 + interval)
            {
                ticks1 = Stopwatch.GetTimestamp();

                MoveGraphics();
                this.Refresh(); 
            }

            Thread.Sleep(1); 
        }
    }

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        Graphics g = e.Graphics;
        Rectangle rect = new Rectangle(renderpoint, 0, 100, 100);
        Color lowcolor = Color.FromArgb(0, 128, 64);
        Color highcolor = Color.FromArgb(0, 128, 64);

        ImageAttributes imageAttr = new ImageAttributes();
        imageAttr.SetColorKey(lowcolor, highcolor);

        if (lastimage == 1)
        {
            lastimage = 0;
            g.DrawImage(dude[1], rect, 0, 0, 100, 100, GraphicsUnit.Pixel, imageAttr);
        }
        else
        {
            lastimage = 1;
            g.DrawImage(dude[0], rect, 0, 0, 100, 100, GraphicsUnit.Pixel, imageAttr);
        }  
    }

    void MoveGraphics()
    {
        if (renderpoint > 950)
        {
            renderpoint = 0;
        }
        else
        {
            renderpoint += 10;
        }
    }
}

There's the current code. Suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Paste this into your Form1 constructor:

this.DoubleBuffered = true;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...