0

我正在制作自定义用户控件,但是当我覆盖时OnPaint(),它不会连续调用。
这是我的代码:

    [ToolboxData("<{0}:ColoredProgressBar runat=server></{0}:ColoredPorgressBar>")]
    public class ColoredProgressBar : ProgressBar
    {
        public Timer timer;

        public ColoredProgressBar()
        {
            timer = new Timer();
            timer.Interval = 1000;
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();
            SetStyle(ControlStyles.DoubleBuffer, true);
            SetStyle(ControlStyles.UserPaint, true);
        }
        public void timer_Tick(object sender , EventArgs e)
        {

        }
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            // Call methods of the System.Drawing.Graphics object.
            e.Graphics.DrawString(Text, Font, new SolidBrush(ForeColor), ClientRectangle);
            Console.WriteLine("???");
        }
    }

我等了 10 秒,消息“???” 应该不断出现在我的控制台中,错误我只看到 12 条消息出现。我试过Invalidate(true);虽然消息不断出现,但表格很滞后。

e.Graphics.DrawString不是很贵的方法吧?

我怎样才能OnPaint() 无延迟地连续通话?

4

1 回答 1

1

您代码中的所有内容都可以正常工作。WinForms 只是 WinApi 和 GDI+ 之上的一个框架,因此您必须首先了解一些有关 Windows 内部消息泵及其发送的消息的知识,您可以在此处阅读。
如您所见WM_PAINT,WinForms 使用一条消息来重新绘制控件。

在您的应用程序收到消息OnPaint后调用每个事件。WM_PAINT您当然可以通过使用Invalidate()不会强制同步绘制例程的方法来强制此消息,如 msdn 页面上所述,您必须在Update()之后调用它应该用作:

this.Invalidate();
this.Update();

或者您可以直接调用Refresh()将强制重绘控件及其所有子控件的方法。

于 2017-04-04T07:53:51.720 回答