Hieu Ha

Hieu Ha

  • NA
  • 24
  • 1.9k

winform c# onPaint() block UI

Oct 30 2017 2:25 AM
I have two UserControls which added in a form in my winforms project, one with the function to draw a string and make it scrolling from right to left and the other draw another string and make it scroll from bottom to top over and over again controlled by calling Invalidate() inside a while(true) loop.But when one of my string becomes too long, about 1000 characters the UI Thread is blocked, so my questions are: What am I doing wrong? is there a better way to make text scrolling??? and bellow is my snippet of code:
  1. int scrollTextSpeed = 100;  
  2. bool scrollingText = true;  
  3. Thread updateUI ;  
  4. void init()  
  5. {  
  6. updateUI = new Thread(updateScrollText);  
  7. updateUI.Start(); } void updateScrollText() { while (true)  
  8. {  
  9. if (scrollingText)  
  10. {  
  11. Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, new MethodInvoker(Invalidate)); Thread.Sleep(scrollTextSpeed);  
  12. }  
  13. }  
  14. }  
  15. protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)  
  16. {  
  17. SizeF stringSize = e.Graphics.MeasureString(text, this.Font);  
  18. var yPos = (this.ClientSize.Height / 2) - (stringSize.Height / 2);  
  19. e.Graphics.TextRenderingHint = TextRenderingHint.AntiAlias; e.Graphics.DrawString(text, this.Font, brus, currentPos, yPos);  
  20. if (fisttime)  
  21. {  
  22. currentPos = this.ClientSize.Width - 1;  
  23. fisttime = false;  
  24. }  
  25. else  
  26. {  
  27. if (currentPos < (-1 * (stringSize.Width)))  
  28. currentPos = this.ClientSize.Width - 1;  
  29. else  
  30. currentPos -= scrollPixelDistance;  
  31. }  
  32. }

Answers (3)