简体   繁体   中英

OnPaint override is never called

I have been at this for a few days and it is driving me mad. I have a control that inherits from System.Windows.Forms.Panel and I'm trying to override OnPaint. It just plain, outright IGNORES it.

public class CollapsiblePanel : System.Windows.Forms.Panel
{
  public CollapsiblePanel()
  {
   //
   // Required for the Windows Form Designer
   //
   InitializeComponent();

   //
   // TODO: Add any constructor code after InitializeComponent call
   //
   SetStyle
    (
     ControlStyles.AllPaintingInWmPaint | 
     ControlStyles.UserPaint      | ControlStyles.DoubleBuffer   |
     ControlStyles.ResizeRedraw     | ControlStyles.Selectable ,
     true
    );
        }

  protected override void OnPaint(PaintEventArgs e)
  {
            // This never runs no matter what I try!
            base.OnPaint(e);
        }
}

I have the same problem just with a ProgressBar, when i try to override the OnPaint.. It's never called.


I found the solution here: http://web.archive.org/web/20140214234801/http://osix.net/modules/article/?id=826

You must create a constructor and enable user-painting like this:

SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw, true);

Default values, probably vary depending on framework version and OS.

如果要调用OnPaint ,请调用this.Invalidate()

I had the problem of not seeing that it was running sometimes. But this works RIGHT AWAY on Windows 7 x64, .NET Framework 4.0. Just added it to a form.

class Class1 : Panel
{
    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        Console.WriteLine("hello world, I'm painting myself");
        // Process.Start("notepad.exe");
    }
}

If you can't see the console output try the Process.Start(...) line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM