2017-04-04 48 views
0

我正在做一個自定義的用戶控件,但是當我覆蓋OnPaint()時,它不會連續調用。
這是我的代碼:c#如何連續調用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()

+0

那麼你不會導致窗口重繪在該代碼中的任何地方。也許你應該在'timer_Tick()'裏面做一些事情,比如'this.Invalidate()'或'this.Refresh()'...... –

+0

這項工作!謝謝各不相同!^_ ^ – Ben

回答

1

代碼中的所有內容都按照原樣運行。 WinForms只是WinApi和GDI +之上的一個框架,因此您必須首先獲得有關Windows內部消息泵和消息的一些知識,這些消息可以發送給您,您可以閱讀其中的內容here
正如你所見,有一個WM_PAINT消息被WinForms用來重新繪製控件。

每個OnPaint事件在您的應用程序收到WM_PAINT消息後調用。您可以通過使用像Invalidate()方法,這將不會強迫繪畫常規同步MSDN頁面上所述的過程中迫使這個消息,你得打個電話Update()後應使用:

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

也可以直接調用Refresh()方法將強制重繪您的控件及其所有的孩子。