Sorry if this has been asked before.
I was working on a simple connect 4 game in C# windows forms as I haven't done any work involving graphics before. To do this I need the program to draw circles when a button is pressed however I don't know how to call the function to do so.
public void printToken(PaintEventArgs pe, int x)
{
Graphics g = pe.Graphics;
Pen blue = new Pen(Color.Blue);
Pen red = new Pen(Color.Red);
Rectangle rect = new Rectangle(50 + ((x-1) * 100), 50, 50, 50);
g.DrawEllipse(blue, rect);
}
private void button1_Click(object sender, EventArgs e)
{
printToken(null, 1);
}
The null in place is just a placeholder as obviously that will not work.
Any and all help is appreciated.
Typically in a Windows Forms application where you want to do custom drawing, you either draw directly on a
Form
orPictureBox
in thePaint
event handler or create a subclass ofControl
in which you override theOnPaint
method. In thePaint
event handler orOnPaint
, you draw everything (i.e. not just one circle, but all the circles). Then when your underlying data structure changes, indicating that you need a repaint, you callInvalidate()
on the control, which marks it as needing redraw, and on the next pass through the event loop, yourPaint
event handler will run or yourOnPaint
method will be called. Within that method, you'll have thePaintEventArgs
object you need to get aGraphics
object with which to do your drawing. You don't want to "draw once and forget" (e.g. when a button is clicked) because there are all sorts of things that can cause your control to need to repaint itself. See this question and answer for more details on that.Edit: here's some hand-holding in response to your comment. (It was going to be a comment but it got too long.)
If I assume for the moment that you're starting with a blank
Form
in Visual Studio's Windows Forms Designer, the quickest way to get going would just be to select theForm
, and in VS's Properties pane, click the lightning bolt toolbar button to view the form's events. Scroll down to thePaint
event and double-click anywhere in the blank space to the right of the label. That will wire up aPaint
event handler for the form and take you to the newly added method in the form's code file. Use thePaintEventArgs
object callede
to do your drawing. Then, if you need to change what gets drawn upon some button click, in your click handler change the data that determine what gets drawn (e.g. positions and colors of of the playing pieces) and, when you're done, callInvalidate()
.