Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Graphics drawing problem

Status
Not open for further replies.

MJB3K

Programmer
Jul 16, 2004
524
GB
Hi, Can anyone give me an answer to this problem I am facing. Here is the code:
Code:
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        Graphics g;

        Brush solBrush = new SolidBrush(Color.Blue);

        public Form1()
        {
            InitializeComponent();

            g = pictureBox1.CreateGraphics();

            g.FillRectangle(solBrush, 10, 10, 100, 30);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            g.FillRectangle(solBrush, 10, 10, 100, 30);
        }
    }
}
When I run this code, how come it won't draw a rectangle in the Form1() constructor, but it will when i click on the button?

Any way of making it being able to draw it on the Form1() constructor?

I am having to call a timer with a 10ms interval at the moment to make it draw.

Regards,

Martin

Computing Design And Services:
 
You can put is on a Form_Load method anyway, I bet it will work there.
 
It is not enough to just paint on the Form_Load. As long as the window is not yet visible on the screen, your drawing will be lost (that is why you used a timer).

note: if want to paint on the form_load event, you can still do so by calling Show(), then draw; not recommended.

The appropriate event for draw operations would be the Paint event, as this is fired every time (only when) the system needs to refresh the UI (as opposed to a normal timer, which repaints even when it does need to).

Also, do not forget to dispose the Graphics object you created from CreateGraphics() method. The Paint event, however, will already provide the Graphics object, but don't dispose this one.
 
As long as the window is not yet visible on the screen, your drawing will be lost (that is why you used a timer).
To correct my post...

As long as the window is not yet visible on the screen, or some portion of it was obscured by other windows or went off-screen, your drawing is lost. This is why you needed the timer to make sure the drawing is persisted.

2cents =)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top