hi everyone,
i'm new in c#, so i have some questions:
i have this piece of code:

Graphics gfx = this.CreateGraphics();
Pen myPen = new Pen(Color.Azure, 1.0f);
Rectangle myRec = new Rectangle(10, 10, 30, 30);
gfx.DrawRectangle(myPen, myRec);

and i want the rectangle myRec appear on the form1 when i press Ctrl+F5. Where should i put it?? On the Form1.cs or on the Form1.Designer.cs?? What is the difference? And i don't understand the methods:

protected override void OnPaint(PaintEventArgs e) {}
private void Form1_Load(object sender, EventArgs e){}
private void Form1_Paint(object sender, EventArgs e){}

Are they events or what? Why when i put that piece of code in Form1_Load or Form1_Paint nothing happens? In which cases i should use each of them? What is the purpose of each of them?
I will be very glad if somebody gives me clear explanation! Sorry if questions are too stupid...

Recommended Answers

All 19 Replies

Put your code in the Form1_Paint method.
Leave out the CreateGraphics, the EventArgs argument is kind enough to provide you one : e.Graphics
The OnPaint method calls the Paint event of the form so I would leave that for now.
You should have a KeyDown event handler where you could capture your key sequence. Then force a redraw of the form(calls your form Paint handler) by calling form.Refresh();

if you only want to draw the rectangle when the user presses a certain key i would use a boolean flag:

private bool keyPressed = false;

private void Form_Paint(object sender, EventArgs e)
{
    if(keyPressed)
    {
          Graphics gfx = e.Gaphics;
          Pen myPen = new Pen(Color.Azure, 1.0f);
          Rectangle myRec = new Rectangle(10, 10, 30, 30);
          gfx.DrawRectangle(myPen, myRec);
    }
}

private void Form_KeyPress(object sender, EventArgs e)
{
        if(true) //change this to check for required key combo
            keyPressed = true;
        else
            keyPressed = false;
}

I typed the above on the fly so the EventArgs probably arent the right ones for the event handlers and you'll need to write a condition to check for the right keypresses but it should get you going in the right direction :)

1. EventArgs e does not even have Graphics field. PaintEventArgs has one.
Error 1 'System.EventArgs' does not contain a definition for 'Graphics' C:\...\Application Data\Temporary Projects\WindowsApplication1\Form1.cs 31 21 WindowsApplication1

private void Form1_Paint(object sender, EventArgs e)
        {
            myPen = new Pen(Color.Azure, 5.0f);
            gfx = e.Graphics; //mistake
            myRec = new Rectangle(10, 10, 50, 50);
            gfx.DrawRectangle(myPen, myRec);
        }

2. I've tried my code in Form1_Paint() method, but when i'm debugging it i see just empty Form. But in the OnPaint() method everything is ok, i see my rectangle.

protected override void  OnPaint(PaintEventArgs e)
        {
            myPen = new Pen(Color.Azure, 5.0f);
            gfx = e.Graphics;
            myRec = new Rectangle(10, 10, 50, 50);
            gfx.DrawRectangle(myPen, myRec);
        } //this draws rectangle as i want

3.WHY??????

You misled me in some way, of course a Paint event handler recieves a PaintEventArgs argument private void Form1_Paint(object sender, PaintEventArgs e)
Form1_Paint(object sender, EventArgs e) normally does not exist unless you created it yourself.

Ok, firstly, i did say at in my post that i typed it on the fly so the eventargs would be the wrong type. I was trying to demonstrate the boolean flag rather than give you the code for the whole thing.

Secondly, i used the code you provided for the rectangel and you are drawing with an Azure brush..that doesnt show up very well on the default grey background of a form.

Thirdly, OnPaint is run when the control needs to be painted, and it subsequently calls the Paint method. The sequence is:
Form Invalidated -> OnPaint executes -> OnPaint method raises Paint event -> Event handlers registered against Paint event execute

If you just typed the code i gave you then the event handlers wont fire. See my tutorial to see what i mean.
If you register a Paint event correctly it will run your code when the form is painted.
If you override the OnPaint you replace the method that usually calls the Paint event. If you dont then include a call to "base.OnPaint(e);" the paint event for your Form wont fire.

You misled me in some way, of course a Paint event handler recieves a PaintEventArgs argument private void Form1_Paint(object sender, PaintEventArgs e)
Form1_Paint(object sender, EventArgs e) normally does not exist unless you created it yourself.

It was my fault ddanbe. I posted some sample code which i wrote freehand in the post rather than in VS. I was demonstrating the use of a boolean flag so didnt take the time to write the correct EventArg types.

I did explain it in the post but it still caused some confusion. I was hopign that the OP either knew enough to chagne it or had already created the event handlers through the designer so they would be hooked up to the events properly...my bad

Don't blame yourself Ryshad, your code written on the fly was actually quite good! (The Gaphics thing on line 8! :D )
I was referring to the OP who also used EventArgs.
Most of the time when I post code, it comes from VS and if possible I even try to run it first. :)

what?? i LOVE my e.Gaphics!! I use them all the time ;)
But seriously, i do normally write and execute my code in VS first, but yesterday was a really hectic day at work. I was squeezing in time between a complex rebuild of my project and a restructuring of my our database to answer a couple of posts :p

Ok ddanbe and Ryshad, thank you very much...)))) I think i should read some materials and puzzle out what is what(i mean these events and methods). It is my first experience in building GUI, so...:))

@Acute: which you all the luck in exploring C#.
Don't hasitate though to post a question!
Events are not the most easy thing to understand ( I still don't understand them fully myself ;) )
Perhaps try this as a starter: http://www.codeproject.com/KB/cs/csevents01.aspx

Hello, it's me again:)
I've got a question:
My Form_Paint() method draws and moves the rectangle using methods MoveRight(), MOveLeft, etc. Also i have Form_MouseClick() event. I want to capture mouse coordinates when user clicks on the form and move my rectangle to that place. If Form_Paint() method draws it, how can i combine it with MouseClick() method??

private void parentWindow_Panel2_MouseClick(object sender, MouseEventArgs e)
        {
            switch (e.Button)
            {
                case MouseButtons.Left:
                    if (MousePosition.X >= myRec.X && MousePosition.X <= myRec.X + 30)
                    {
                        if (MousePosition.Y > myRec.Y)
                        {
                            //down
                        }
                        else
                        {
                            //up
                        }
                    }
                    break;
                case MouseButtons.Right:
                    ...
		    ...
                    break;
		    ...
		    ...	
                default:
                    break;
            }
	...
	...
        }

It depends how you are calculating the Move...() methods.
Personally, i would have class member to store the current location, alter the location in any of the Move/Click methods, then use that member when processing the Form_Paint method.
eg:

public partial class Form1 : Form
    {
        private Point Location = new Point(0, 0);

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            //draw rectangle at Location
        }

        private void MoveDown()
        {
            //move rectangles position down 10 pixels
            Location.Y -= 10;
        }

        private void Form1_MouseClick(object sender, MouseEventArgs e)
        {
            //set rectangle location to mouse click location
            Location = e.Location;
        }

I've already made something similar to your idea, but still i dont know how to insert Form_Paint() event inside of Form_MouseClick().
I have a global class (it's name is gb) and this class stores the current location of mouse when it is clicked on the form. Paint method just takes that coordinates and draws the rectangle. Now, how i can insert Paint method into MouseClick method?? Here is my Code:

private void parentWindow_Panel2_MouseClick(object sender, MouseEventArgs e)
        {
            gb.mouseX = e.X;
            gb.mouseY = e.Y;
            
            switch (e.Button)
            {
                case MouseButtons.Left:
                    gb.mouseButton = 'l';
                    break;
                case MouseButtons.Right:
                    gb.mouseButton = 'r';
                    break;
                default:
                    break;
            }
        }

        private void parentWindow_Panel2_Paint(object sender, PaintEventArgs e)
        {
            Graphics gfx = e.Graphics;
            gfx.DrawRectangle(gb.myPen, gb.myRec);

            if (gb.mouseX >= gb.myRec.X && gb.mouseX <= gb.myRec.X + 30)    //Down and Up
            {
                if (gb.mouseY > gb.myRec.Y) //Down
                {
                    if (gb.mouseButton == 'l')
                    {
                        gb.MoveDown(gfx, gb.mouseY - gb.myRec.Y);
                    }
                    else if (gb.mouseButton == 'r')
                    {
                        gb.JumpDown(gfx, gb.mouseY - gb.myRec.Y);
                    }
                }
                else if (gb.mouseY < gb.myRec.Y)    //Up
                {
                    if (gb.mouseButton == 'l')
                    {
                        gb.MoveUp(gfx, gb.myRec.Y - gb.mouseY);
                    }
                    else if (gb.mouseButton == 'r')
                    {
                        gb.JumpUp(gfx, gb.myRec.Y - gb.mouseY);
                    }
                }
            }
            if (gb.mouseY >= gb.myRec.Y && gb.mouseY <= gb.myRec.Y + 30)    //Right and Left
            {
                if (gb.mouseX > gb.myRec.X) //Right
                {
                    if (gb.mouseButton == 'l')
                    {
                        gb.MoveRight(gfx, gb.mouseX - gb.myRec.Y);
                    }
                    else if (gb.mouseButton == 'r')
                    {
                        gb.JumpRight(gfx, gb.mouseX - gb.myRec.X);
                    }
                }
                else if (gb.mouseX < gb.myRec.X)    //Left
                {
                    if (gb.mouseButton == 'l')
                    {
                        gb.MoveLeft(gfx, gb.myRec.X - gb.mouseX);
                    }
                    else if (gb.mouseButton == 'r')
                    {
                        gb.JumpLeft(gfx, gb.myRec.X - gb.mouseX);
                    }
                }
            }
        }

Shortly, i want Paint() method to work just after MouseClick() everytime when MouseClick is detected.

You should try to avoid replicating issues on the forum. You have a seperate thread to discuss your issue calling the Paint event.
As i have said there twice; you raise a paint event by invalidating the control. If its a Form you want to paint then call this.Invalidate(), if its a panel then call this.Panel1.Invalidate().
Once invalidated, the control will be redrawn, raising a Paint event.

In your case it would be something like:

private void parentWindow_Panel2_MouseClick(object sender, MouseEventArgs e)
        {
            gb.mouseX = e.X;
            gb.mouseY = e.Y;
            
            switch (e.Button)
            {
                case MouseButtons.Left:
                    gb.mouseButton = 'l';
                    break;
                case MouseButtons.Right:
                    gb.mouseButton = 'r';
                    break;
                default:
                    break;
            }
        parentWindow_Panel2.Invalidate() //assuming parentWindow_Panel2 is the name of teh control you want to redraw
        }
parentWindow.Panel2.Invalidate();

is the solution, man!! Thank you so much!!

P.S.: Invalidate() means like restart the Form?

Not exactly, it marks the form as needing to be repainted. If you open a form and then drag another window over part of it, the part that is covered is marked invalidated. If you minimise the form the whole thing is marked as invalidated.
If part of a control is marked as invalidated then the system knows that it needs to be redrawn.

Its worth noting that when Invalidated the form wont repaint right away. It paints when the app is next idle. Usually this isnt a problem, but if your app is going to be busy and you need it to repaint right away you can call Control.Refresh(). This forces any invalidated areas to be redrawn now rather than when the app is idle.

Ookey... in my case when left button of mouse is clicked, the rectangle must leave print(footprint, trace) while moving, but Invalidate() clears everything...:( how can i fix it??
thnx in advance:)

so you want the rectangle to be animated as it moves across the form?
Thats a whole new topic. Start a new thread rather than branching from a solved one, that way it keeps the distinct problems seperate :)

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.