0

So I have this code where I want to call the set_background void in the resize_Handler void. How would I do that? I tried set_background(null, PaintEventArgs()); inside the resize_Handler, but it says non-invocable member cannot be used like a method.

My code:

private void set_background(Object sender, PaintEventArgs e) {
    Graphics graphics = e.Graphics;

    Rectangle gradient_rectangle = new Rectangle(0, 0, Width, Height);

    Brush b = new LinearGradientBrush(gradient_rectangle, Color.FromArgb(255, 255, 255), Color.FromArgb(255, 102, 54), 0f);
 
    graphics.FillRectangle(b, gradient_rectangle);
}

private void resize_Handler(object sender, System.EventArgs e) {
    // where I want to call set_background()
}
  • `PaintEventArgs` is a type - so `PaintEventArgs()` isn't valid. But `new PaintEventArgs()` would be. – Jon Skeet Nov 30 '21 at 20:44
  • Although I have to ask what you'd expect `e.Graphics` to be in that case... fundamentally these methods are expected to be used as event handlers rather than called directly. – Jon Skeet Nov 30 '21 at 20:46
  • @JonSkeet, but I want it to be called when the window resizes. Can you provide some information about that. I tried doing ```set_background(null, new PaintEventArgs(null, new Rectangle()));```, but it also didn't work either. Thanks in advance. – Sabawoon Enayat Nov 30 '21 at 20:54
  • Actually I think the solution is `this.Invalidate()` or `this.Update()` or `this.Refresh()` (combination of both). Otherwise the problem will be that you don't know which graphics object to use. You have probably hooked that up to the [Paint event](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.paint?view=windowsdesktop-6.0) anyway, just with a strange name. – Thomas Weller Nov 30 '21 at 21:10

1 Answers1

0

Instead of trying to call an event handler directly, refactor the code in the event handler to its own method, and call the new method instead.

private void SetBackground(Graphics graphics)
{        
    Rectangle gradient_rectangle = new Rectangle(0, 0, Width, Height);

    Brush b = new LinearGradientBrush(gradient_rectangle, Color.FromArgb(255, 255, 255), Color.FromArgb(255, 102, 54), 0f);
 
    graphics.FillRectangle(b, gradient_rectangle);
}

private void set_background(Object sender, PaintEventArgs e) {
   SetBackground(e.Graphics);
}

private void resize_Handler(object sender, System.EventArgs e) {
   Graphics graphics = new Graphics(); // or whatever applies here.
   SetBackground(graphics);
}
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501