Home > database >  Call event using button c#
Call event using button c#

Time:08-28

I'm trying to call PaintEventArgs when i press a button, my problem is i don't know how to call one without modify button event

    private void button_Click(object sender, EventArgs e /*<= PaintEventArgs*/)
    {
        func(e);
        base.OnPaint(e);
    }

CodePudding user response:

You can call Invalidate() It will cause the control to be redrawn

    private void button_Click(object sender, EventArgs e /*<= PaintEventArgs*/)
    {
        //func(e); It will be called in the OnPaint method
        Invalidate();
    }

To use PaintEventArgs you need to override OnPaint method

protected override void OnPaint(PaintEventArgs e)
{
   base.OnPaint(e);
   func(e);
}

To implement the OnPaint you need to create your own class that inherits the Button

public class BetterButton : Button{
   public BetterButton() 
   {}
   protected override void OnPaint(PaintEventArgs e) {
      base.OnPaint(e);      
      func(e);
   } 
}

CodePudding user response:

You ALWAYS do the drawing on the Paint event of the control you want to draw on. That might mean in the overridden OnPaint method or else in the Paint event handler. In order to cause thew Paint event to be raised, you call the Invalidate method of the appropriate control. You can call it with no arguments but, ideally, you would calculate the smallest area that has or might have changed and pass that as a Rectangle or the like.

EDIT:

Here is an example that will draw the last recorded time in the top-left of the form and update that time on each click of a Button:

private DateTime time;

private void button1_Click(object sender, EventArgs e)
{
    time = DateTime.Now;
    Invalidate();
}

private void Form1_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.DrawString(time.ToString(), Font, Brushes.Black, 10, 10);
}

As you can see, all you need to do on the Click event is update the data and invalidate the form. All the drawing, including the PaintEventArgs, is taken care of in the Paint event handler.

  • Related