1

Clicking a button from windows form it doesn't work.

Because, I have to use the parameters "Graphics g..." for the methods. I can't change the methods so, I have to change something when the user clicks the button.

Below is the code:

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

//protected override void OnPaint(PaintEventArgs e)
    //{
    //    Graphics g = e.Graphics;
    //    TekenCirkel(g, 50, 50, 100, 100);
    //    TekenRechthoek(g, 0, 0, 100, 100);
    //}

    public void TekenCirkel(Graphics g, int x, int y, int w, int h) {
        Pen cirkel = new Pen(Color.Blue, 2);
        g.DrawEllipse(cirkel, x,y, w, h);
    }

    public void TekenRechthoek(Graphics g, int x, int y, int w, int h){
        Pen rechthoek = new Pen(Color.Black, 2);
        g.DrawRectangle(rechthoek, x, y, w, h);
    }

    private void Cirkel_Click(object sender, EventArgs e)
    {

        TekenCirkel(g, 50, 50, 100, 100);
    }
}

As you can see I tested it with the onPaint method and defining what g does. When using this method the code works. But that isn't possible when trying to click the button. Because EventArgs and PaintEventArgs are different things.

E: You click a button and a cirkel/square gets painted on the form. I want to know how to call a method I created to draw the cirkel/ square.

1 Answers1

3

That's not how painting works.

You must paint everything from OnPaint() only, using data structures in your class to track what you want to paint.

You then call Invalidate() to make it repaint if you want to change it.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • actually, it *can* work like that, so you don't *necesarily* have to do this (although i agree this is a neater solution) – Timothy Groote Oct 31 '17 at 16:14
  • 1
    @TimothyGroote: Until something repaints your form, at which point it will break. – SLaks Oct 31 '17 at 16:16
  • that's exactly why this is better ;) – Timothy Groote Oct 31 '17 at 16:16
  • so what you mean is that when someone clicks the button the click event refers to the OnPaint() event and the OnPaint() event will call the methods? – SupremeLeader Oct 31 '17 at 17:24
  • 1
    @SupremeLeader: Yes, via `Invalidate()`. – SLaks Oct 31 '17 at 17:59
  • @SLaks But how do I refer to onpaint()? Do I have to do something like OnPaint(Methode_naam(Methode_values)) or just put in the action click invalidate? – SupremeLeader Oct 31 '17 at 18:48
  • You need to call `Invalidate()`. – SLaks Oct 31 '17 at 18:52
  • oh I see when you click the button the code behind it says invalidate. Thanks! But how do you know which button is called so in the methode it only shows the cirkel or the square? I could use a bool but is there a better way? – SupremeLeader Oct 31 '17 at 18:57
  • 1
    @SupremeLeader: You need to keep track of everything you want to be drawn at all times. You probably want a list of some class. – SLaks Oct 31 '17 at 19:03