Pyr0lle
Pyr0lle

Reputation: 80

Why is my screen flickering even though I have double buffering on?

Ok, Im pretty new to c# graphics and I'm trying to make a top down adventure game type thing. The problem is anything displayed above the background flickers. Everything is a bitmap from a png file. The background doesnt flicker so I dont know where I'm going wrong. Here's my code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AITS
{
    public partial class Form1 : Form
    {
        Background background;
        Foreground foreground;
        Character player;
        Graphics g;

        public Form1()
        {
            InitializeComponent();
            Console.WriteLine(Environment.CurrentDirectory);
            background = new Background(Properties.Resources.background, Width, Height);
            foreground = new Foreground(100, Width);
            player = new Character();
            DoubleBuffered = true;


            Paint += DrawScreen;
            KeyDown += KeyPressed;
            Shown += Form1_Shown;

            g = CreateGraphics();

        }

        private void Form1_Shown(Object sender, EventArgs e)
        {
            gameLoop();
        }

        private void DrawScreen(object sender, PaintEventArgs args)
        {
                background.Draw(g);
                player.Draw(g);
                foreground.Update(Height, Width);
                foreground.Draw(g);
        }

        private void KeyPressed(object sender, KeyEventArgs e)
        {
            Console.WriteLine(e.KeyData.ToString());
        }

        public void gameLoop()
        {
            while (this.Created)
            {
                Invalidate();
                Refresh();
                Application.DoEvents();

            }   
        }
    }
}

EDIT: Ok i found the answer, for anyone who couldnt find this like me: g should = args.Graphics. DO NOT use CreateGraphics()!

Upvotes: 1

Views: 196

Answers (2)

Pyr0lle
Pyr0lle

Reputation: 80

Ok i found the answer, for anyone who couldnt find this like me: g should = args.Graphics. DO NOT use CreateGraphics()!

Upvotes: 1

Nick
Nick

Reputation: 5042

The screen flickers, because the form first redraws its background before letting you paint on it.

You can suspend this behavior by overriding WndProc:

private const int WM_ERASEBKGND = 20;        
protected override void WndProc(ref Message m)
{
    if (m.Msg == WM_ERASEBKGND)
    {
        m.Result = IntPtr.Zero;
    }
    else
    {
        base.WndProc(ref m);
    }
}

Upvotes: 1

Related Questions