Bobby
Bobby

Reputation: 2938

Trouble displaying an Image on my Panel

I'm trying to draw images for a game on to a Panel in C#. I get no images being drawn and I can't figure out why this method is never called:

private void playerPanel_Paint(object sender, PaintEventArgs e)

Here is 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 FlightOfTheNavigator
{
    public partial class Form1 : Form
    {
        // Load Sprites
        public Bitmap playerShip = new Bitmap(FlightOfTheNavigator.Properties.Resources.testship);

        public Form1()
        {
            InitializeComponent();        
            SetupGame();
        }

        public void SetupGame()
        {
            // Setup Console
            txtConsole.Text = "Loading Ship Bios v3.4.12c ..." + 
                               Environment.NewLine + 
                               "Console Ready" + 
                               Environment.NewLine + 
                               "----------------------------------------------------------------------------------------" + 
                               Environment.NewLine +
                               Environment.NewLine;

            // Setup Basic Weapons
            listWeapons.Items.Add("Pulse Lazers");
            listWeapons.Items.Add("Cluster Missiles");

            // Set Shield Perecentage
            txtShields.Text = "0%";
        }

        private void trackShield_Scroll(object sender, EventArgs e)
        {
            txtShields.Text = "" + trackShield.Value + "%";
        }

        private void playerPanel_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = playerPanel.CreateGraphics();
            g.DrawImage(playerShip, 0, 0,100,100);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Invalidate the panel. This will lead to a call of 'playerPanel_Paint'
            playerPanel.Refresh();
        }
    }
}

Upvotes: 0

Views: 239

Answers (1)

Moha Dehghan
Moha Dehghan

Reputation: 18472

Make sure the Paint event of the panel is attached to playerPanel_Paint method.

Open the Desinger, select the panel (playerPanel), press F4 to bring up the Properties window, then click the lightning bolt above the Properties window to show the events. Check the Paint event there. If it is empty, open the drop-down and select playerPanel_Paint method.

You can also do it in code. Put this into the form's constructor after InitializeComponent():

this.playerPanel.Paint += PaintEventHandler(playerPanel_Paint);

Upvotes: 1

Related Questions