Hi everyone! While writing one of my first programs in C# I have encountered a problem: I create two PictureBoxes(1 and 2) and I want PainEvent to draw a line on second of them(PictureBox2). When i start my program there isn't any line on it and it appears when I move entire window. Here is the code: I would be really grateful if somebody could solve my problem. I think it's trival but i can figure it out.

Bitmap bm;
public Form1()
{
InitializeComponent();
bm = new Bitmap(pictureBox1.Width, pictureBox1.Height);
pictureBox1.Image = bm;
pictureBox2.Image = (Bitmap)bm.Clone();
}
private void Form1_Load(object sender, EventArgs e)
{
Graphics g = Graphics.FromImage(pictureBox1.Image);
Rectangle re = new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height);
pictureBox2.Image = (Bitmap)bm.Clone();
g.Dispose();
}
private void pictureBox2_Paint(object sender, PaintEventArgs e)
{
Graphics g = Graphics.FromImage(pictureBox2.Image);
g.DrawLine(new Pen(new SolidBrush(Color.RoyalBlue), 15), new Point(pictureBox2.Width, 0), new Point(0, pictureBox2.Height));
g.Dispose();

}

Recommended Answers

All 4 Replies

This works:

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void pictureBox2_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            g.DrawLine(new Pen(new SolidBrush(Color.RoyalBlue), 15), 
                new Point(pictureBox2.Width, 0), 
                new Point(0, pictureBox2.Height));
        }
    }
}

Just copied line 19 of your code and made use of the fact that PaintEventArgs offers a Graphics object for free.

You can also call Invalidate(); anywhere within your code to force the Paint() method to run.

Thank you very much! It's helped! Althought the line:

Graphics g = e.Graphics;

compiles but while running it causes errors and the window closes

What is the exception or error message that pops up?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.