永远不会调用OnPaint覆盖
我已经在这里待了几天,这让我很生气。 我有一个inheritance自System.Windows.Forms.Panel的控件,我试图覆盖OnPaint。 它很简单,直截了当地说它。
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); } }
当我尝试覆盖OnPaint时,我对ProgressBar也有同样的问题。它永远不会被调用。
我在这里找到了解决方案: http : //web.archive.org/web/20140214234801/http : //osix.net/modules/article/?id = 826
您必须创建一个构造函数并启用用户绘制,如下所示:
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw, true);
默认值可能因框架版本和操作系统而异。
如果要调用OnPaint
,请调用this.Invalidate()
我有一个问题,就是没有看到它有时会运行。 但这适用于Windows 7 x64,.NET Framework 4.0。 刚刚将它添加到表单中。
class Class1 : Panel { protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); Console.WriteLine("hello world, I'm painting myself"); // Process.Start("notepad.exe"); } }
如果您看不到控制台输出,请尝试Process.Start(...)
行。