代码之家  ›  专栏  ›  技术社区  ›  Bloodyaugust

如何修复winforms窗体中的闪烁?

  •  15
  • Bloodyaugust  · 技术社区  · 16 年前

    我经常画框,我需要的形式不闪烁。我该怎么做?

    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;
            }
        }
    }
    

    这是当前代码。建议?

    2 回复  |  直到 13 年前
        1
  •  12
  •   Hans Passant    16 年前

    将此粘贴到Form1构造函数中:

    this.DoubleBuffered = true;
    
        2
  •  12
  •   Frank Krueger    16 年前
    1. 在 Paint 事件处理程序
    2. 禁用背景的自动擦除。
    3. 通过样式或手动启用双缓冲。
    4. 当你想重新粉刷时,打电话给 Invalidate

    如果你想画出平滑的动画,那么我建议你跳到wpf、opengl或xna。gdi+不是为动画而设计的(windows消息循环不是一个实时系统,因此您总是会感到不安)。

    推荐文章