Why do my WinForms controls flicker and resize slowly? - c#

I'm making a program where I have a lot of panels and panels in panels.
I have a few custom drawn controls in these panels.
The resize function of 1 panel contains code to adjust the size and position of all controls in that panel.
Now as soon as I resize the program, the resize of this panel gets actived. This results in a lot of flickering of the components in this panel.
All user drawn controls are double buffered.
Can some one help me solve this problem?

To get rid of the flicker while resizing the win form, suspend the layout while resizing. Override the forms resizebegin/resizeend methods as below.
protected override void OnResizeBegin(EventArgs e) {
SuspendLayout();
base.OnResizeBegin(e);
}
protected override void OnResizeEnd(EventArgs e) {
ResumeLayout();
base.OnResizeEnd(e);
}
This will leave the controls intact (as they where before resizing) and force a redraw when the resize operation is completed.

Looking at the project you posted, the flickering is really bad when you have the first tab selected, with the gradient-filled group boxes. With the second or third tab showing, there's hardly any flicker, if at all.
So clearly the problem has something to do with the controls you're showing on that tab page. A quick glance at the code for the custom gradient-filled group box class gives away the more specific cause. You're doing a lot of really expensive processing each time you draw one of the groupbox controls. Because each groupbox control has to repaint itself each time the form is resized, that code is getting executed an unbelievable number of times.
Plus, you have the controls' background set to "Transparent", which has to be faked in WinForms by asking the parent window to draw itself first inside the control window to produce the background pixels. The control then draws itself on top of that. This is also more work than filling the control's background with a solid color like SystemColors.Control, and it's causing you to see the form's pixels being drawn while you resize the form, before the groupboxes have a chance to paint themselves.
Here's the specific code I'm talking about from your custom gradient-filled groupbox control class:
protected override void OnPaint(PaintEventArgs e)
{
if (Visible)
{
Graphics gr = e.Graphics;
Rectangle clipRectangle = new Rectangle(new Point(0, 0), this.Size);
Size tSize = TextRenderer.MeasureText(Text, this.Font);
Rectangle r1 = new Rectangle(0, (tSize.Height / 2), Width - 2, Height - tSize.Height / 2 - 2);
Rectangle r2 = new Rectangle(0, 0, Width, Height);
Rectangle textRect = new Rectangle(6, 0, tSize.Width, tSize.Height);
GraphicsPath gp = new GraphicsPath();
gp.AddRectangle(r2);
gp.AddRectangle(r1);
gp.FillMode = FillMode.Alternate;
gr.FillRectangle(new SolidBrush(Parent.BackColor), clipRectangle);
LinearGradientBrush gradBrush;
gradBrush = new LinearGradientBrush(clipRectangle, SystemColors.GradientInactiveCaption, SystemColors.InactiveCaptionText, LinearGradientMode.BackwardDiagonal);
gr.FillPath(gradBrush, RoundedRectangle.Create(r1, 7));
Pen borderPen = new Pen(BorderColor);
gr.DrawPath(borderPen, RoundedRectangle.Create(r1, 7));
gr.FillRectangle(gradBrush, textRect);
gr.DrawRectangle(borderPen, textRect);
gr.DrawString(Text, base.Font, new SolidBrush(ForeColor), 6, 0);
}
}
protected override void OnPaintBackground(PaintEventArgs pevent)
{
if (this.BackColor == Color.Transparent)
base.OnPaintBackground(pevent);
}
And now that you've seen the code, red warning flags ought to go up. You're creating a bunch of GDI+ objects (brushes, pens, regions, etc.), but failing to Dispose any of them! Almost all of that code should be wrapped in using statements. That's just sloppy coding.
Doing all of that work costs something. When the computer is forced to devote so much time to rendering controls, other things lag behind. You see a flicker as it strains to keep up with the resize. It's no different than anything else that overloads a computer (like a computing the value of pi), it's just really easy to do so when you use as many custom drawn controls like you do here. Transparency is hard in Win32, and so is a lot of custom 3D painting. It makes the UI look and feel clunky to the user. Yet another reason that I don't understand the rush away from native controls.
You really only have three options:
Deal with the flicker. (I agree, this is not a good option.)
Use different controls, like the standard, built-in ones. Sure, they may not have a fancy gradient effect, but that's going to look broken half of the time anyway if the user has customized their Windows theme. It's also reasonably hard to read black text on a dark gray background.
Change the painting code within your custom controls to do less work. You may be able to get by with some simple "optimizations" that don't cost you any of the visual effects, but I suspect this is unlikely. It's a tradeoff between speed and eye candy. Doing nothing is always faster.

I successfully eliminate flicker when form resize using this code. Thanks.
VB.NET
Public Class Form1
Public Sub New()
Me.SetStyle(ControlStyles.UserPaint Or ControlStyles.OptimizedDoubleBuffer Or ControlStyles.AllPaintingInWmPaint Or ControlStyles.SupportsTransparentBackColor, True)
End Sub
Private Sub Form1_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Resize
Me.Update()
End Sub
End Class
C#
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Resize += Form1_Resize;
this.SetStyle(ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.SupportsTransparentBackColor, true);
}
private void Form1_Resize(object sender, System.EventArgs e)
{
this.Update();
}
}

So I ran into this same problem - my control with a transparent background was repainting like 34 times, and what worked for me was:
On my form that contained the control
protected override void OnResize(EventArgs e)
{
myControl.Visible = false;
base.OnResize(e);
myControl.Visible = true;
}
And the same in the control:
protected override void OnResize(EventArgs e)
{
this.Visible = false;
base.OnResize(e);
this.Visible = true;
}
This reduced the amount of repainting to 4, which effectively eliminated any flicker when the control was being resized.

Maybe a good solution for you will be to use Form.ResizeBegin and Form.ResizeEnd events.
On ResizeBegin set main panel visibility to false, on ResizeEnd set main panel visibility to true.
This way panels will not be redrawn while someone is resizing your form.

While hooking into ResizeBegin and ResizeEnd is the right idea, instead of hiding the main panel's visibility I'd instead delay any resize calculations until ResizeEnd. In this case, you don't even need to hook into ResizeBegin or Resize - all the logic goes into ResizeEnd.
I say this for two reasons. One, even though the panel is hidden, the resize operation will likely still be expensive and so the form won't feel as responsive as it should unless the resize calculations are delayed. Two, hiding the pane's contents while resizing can be jarring to the user.

I had the same problem.
It seams that this is happening because you are using rounded corners. When I set CornerRadius property to 0, the flickering was gone.
So far I have only found the following workaround. Not the nicest one, but it stops the flickering.
private void Form_ResizeBegin(object sender, EventArgs e)
{
rectangleShape.CornerRadius = 0;
}
private void Form_ResizeEnd(object sender, EventArgs e)
{
rectangleShape.CornerRadius = 15;
}

I Had A Similar Issue Like This. My Entire Form Was Resizing Slowly And The Controls Painted Them In An Ugly Manner. So This Helped Me:
//I Added This To The Designer File, You Can Still Change The WindowState In Designer View If You Want. This Helped Me Though.
this.WindowState = FormWindowState.Maximized;
And In The Resize Event, Add This Code To The Beginning
this.Refresh();

Related

Lag when frequently moving and redrawing a control

Moving Label inside parent's MouseMove-events causes trailing redraw.
I am (mis)using System.Windows.Forms.Label objects to realize
A more flexible tooltip,
Displaying a cross hair "cursor" extending to the borders of a parent control.
To that end I create the labels as members of the parent control (btw. it's a custom graphics control with mouse wheel zoom, panning etc.), add them to the parent's Controls-list, and move them inside the MouseMove-event of the parent. In order to ensure crisp movement behavior, I even call Label.Refresh when assigning the Location property of the Labels.
void GraphViewMouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (lastLocation != e.Location)
{
HasMoved = true;
if (IsPanning && e.Button == MouseButtons.Left)
{
if (isSelecting) PerformSelection(e.Location);
else PerformMove(e.Location,lastLocation);
}
lastLocation = e.Location;
if (Width > 0 && Height > 0)
{
PointD pos = CursorPosition;
// nothing interesting, basically like what is done with the crossHair's below
coordinateToolTip.Locate(lastLocation, pos.X, pos.Y);
crossHairX.Location = new Point(lastLocation.X, 0);
crossHairY.Location = new Point(0, lastLocation.Y);
crossHairX.Refresh();
crossHairY.Refresh();
}
}
}
Everything works almost fine (the labels move parallel to the mouse cursor) except that when I move the mouse a little faster, several copies of the Label(s) remain in the client area of the parent for some time like a visual echo.
That is, whereas the redraw of the labels at their new location appears to occur immediately, it seems to take some fraction of a second until the background of the parent (some complicated graphics, the complete redraw of which takes several seconds, but is definitely not redrawn during said simple mouse move) is restored to what has been behind the moving Label(s) originally. This is of course functionally irrelevant, but it simply looks ugly because it raises the impression that the code is inefficient.
Is there a way to enforce (faster) redraw of the cached background graphics? What determines the delay before the screen content behind a control is restored?
Edit: as to the suggestion of setting DoubleBuffered=true: according to MSDN this should already be true by default. Indeed it doesn't make a difference if I set it true for the Label. On the other hand, setting it false introduces additional flickering as expected. In either case the restoration of the background remains delayed, like described above.
#Hans Passant: Thanks for telling us "When you move a control, its parent's OnPaintBackground() method needs to run to over-draw the pixels that were left behind by the control in its previous position."
For me the cp.ExStyle |= 0x02000000; // Turn on WS_EX_COMPOSITED did not work.
I am creating movable, Resizable Panel and when I moved it fast from left to right it was not displayed right "the half of the panel was often gone". I did this and now it works exactly like when I move a Windows Window.
This is in the MyPanel Class which I made and Inherits from Panel
protected override void OnMove(EventArgs e)
{
this.Parent.Invalidate();
base.OnMove(e);
}
So when I move the Movable panel with the mouse it wil Invalidate the "Parrent" in my case the Form and now it moves fine.

Drawing on OnPaint() makes residues when the window is resized

I have created a custom panel that draws a border (that comprises two rectangles). The problem is that if I resize the window, there remain residues... much like the animation of Windows XP's Solitaire. See the screenshot below. I resized the window to the right.
What is wrong, and how can I fix this?
protected override void OnPaint(PaintEventArgs e)
{
var outer = ClientRectangle;
outer.Width -= 1;
outer.Height -= 1;
var inner = outer;
inner.X++;
inner.Y++;
inner.Width -= 2;
inner.Height -= 2;
e.Graphics.DrawRectangle(DarkPen, outer);
e.Graphics.DrawRectangle(WhitePen, inner);
base.OnPaint(e);
}
UPDATE
At first I thought this was because I did not delete the previously drawn rectangles. So I called FillRectangle to delete the inside.
var contentArea = inner;
contentArea.X++;
contentArea.Y++;
contentArea.Width -= 2;
contentArea.Height -= 2;
e.Graphics.FillRectangle(SystemBrushes.Control, contentArea);
But it did not work either. It seems that the control paints only the newly expanded portion, not the entire area.
The Form class was optimized to be a container control. Containers normally just have a background color to paint. So, as you noticed, indeed does "only paint newly expanded portion". Or more accurately, it does not overpaint the previous pixels, easy to recognize from the smearing effect that produces. It is a somewhat feeble attempt at making Winforms designs a bit more lively when you resize the window, painting gets to be a bottleneck when a form has a lot of controls and that is pretty noticeable.
You'll have to set its ResizeRedraw property to true so it redraws its entire surface when necessary. Setting the DoubleBuffered property to true might not hurt either when the drawing code gets elaborate and you start noticing flicker.
So, roughly:
public Form1() {
InitializeComponent();
this.ResizeRedraw = true;
this.DoubleBuffered = true;
}
Optimizing OnPaint() is generally not a strategy that pays off, Windows itself already clips what you draw against the dirty region.

Scroll an image quickly and smoothly

When scrolling an image in a browser using the scrollbars - the image scrolls quickly and smoothly. On the other hand, making a tight loop with Graphics.DrawImage, incrementing the location's X-coordinate by 1 each iteration - returns a slow motion. (It's also somewhat jerky even after making the Control DoubleBuffered.)
How can I get fast rendering like a browser's?
EDIT
void DoNow()
{
Rectangle rec1 = new Rectangle(Point.Empty, panel1.BackgroundImage.Size);
Rectangle rec2 = new Rectangle(Point.Empty, panel1.BackgroundImage.Size);
using (Graphics g = Graphics.FromImage(panel1.BackgroundImage))
{
for (int i = 0; i < 100; i++)
{
rec2.Location = new Point(rec2.Location.X + 1, rec2.Location.Y);
g.DrawImage(image, rec1, rec2, GraphicsUnit.Pixel);
panel1.Refresh();
}
}
}
It seems from the comments like the answer to my question is that browsers use hardware acceleration which is unavailable to Winforms. (Please feel free to correct me if I'm wrong.)
The easiest solution is to use a Panel object with the scroll bars set to Auto. Place a picturebox as a child object with the size mode set to Auto. The picture box will expand to the size of the image that you assign to it. Since the picture box will expand to be larger than the panel, the panel's scroll bars will appear. When you scroll the image using the panel, it will be smooth.
If you still want to manually provide the drawing yourself, you are getting the "flicker" because the Invalidate method automatically performs background erasing which is not performed during the OnPaint event. You need to subclass the parent control that you are drawing on and override the OnPaintBackground event. Like below:
protected override void OnPaintBackground(PaintEventArgs pevent)
{
// base.OnPaintBackground(pevent);
}
Also, remember to perform ALL drawing during the OnPaint event and use the e.Graphics object.

GDI+ drawing becomes corrupted when ClientSize changes

I need to draw a circle with the size of the entire form. I have made a Form1 with the following Paint event handler:
private void Form1_Paint(object sender, PaintEventArgs e)
{
SolidBrush myBrush = new SolidBrush(Color.Black);
e.Graphics.FillEllipse(myBrush, 0, 0, this.ClientSize.Width, this.ClientSize.Height);
}
The problem is that when you change the size of the form or maximize it the drawing becomes corrupted. Please help me how to avoid this problem. Sorry I haven't found an appropriate topic on StackOverflow.
Painting for container controls like Form was optimized, they only redraw the part of the window that was revealed by the resize. In other words, if the user drags the right or bottom edge then there's no repaint at all when the window is made smaller. A small repaint if it is made bigger, only the part of the window to became visible.
This is normally very appropriate since they don't have much reason to completely repaint themselves, they only draw their background. This matters in particular when the user resizes the window by dragging a corner, that can generate a storm of repaint requests. And if repainting is slow then that gets to be very visible, moving the mouse makes the motion "stutter", flicker can be noticeable as well.
But you care, you need to completely redraw the ellipse since you use the ClientSize property in your paint event handler.
Whether or not this optimization is turned on is determined by a style flag for the control, as Sriram pointed out. Turning this off is so common that Winforms exposed the style flag through a simple property to make it easier to change it:
public Form1() {
InitializeComponent();
this.ResizeRedraw = true;
this.DoubleBuffered = true;
}
Note the DoubleBuffered property, another example of a convenience property that actually changed ControlStyles. You want this turned on to suppress the flicker your window exhibits. Caused by first drawing the background, which erases your ellipse, then repainting the ellipse.
There's another pretty serious problem in your code, SolidBrush is a disposable class. Disposing objects is optional, but skipping this for System.Drawing objects is quite unwise. If you resize your window frequently enough, 10000 times, then your program will crash. That sounds like a lot, but it is not when you set ResizeRedraw to true since that generates a lot of repaints. Only the garbage collector can keep you out of trouble, it won't in a simple program like this. Fix:
protected override void OnPaint(PaintEventArgs e) {
using (var brush = new SolidBrush(this.ForeColor)) {
e.Graphics.FillEllipse(brush, 0, 0, this.ClientSize.Width, this.ClientSize.Height);
}
base.OnPaint(e);
}
Btw, do not optimize this by keeping the brush around as recommended in another post. Creating a brush is very cheap, takes about a microsecond. But is far too expensive to keep around, it is allocated on a heap that's shared by all programs that run on the desktop. A limited resource, that heap is small and programs start failing badly when the that heap is out of storage.
You'll have to enable ResizeRedraw. Add the following to your constructor.
this.SetStyle(ControlStyles.ResizeRedraw, true);
On Forms Resize event paste this ;
this.Refresh();
this will redraw the form and fire the Form1.Paint event.
That occurs because only part of the form's area gets invalidated when the size changes. What you need to do is handle the SizeChanged event and call the form's Refresh method.
Call Graphics.Clear(); before drawing to clear the old graphics and avoid creating redundant brushes.Put the code for the Brush creation outside the block
SolidBrush myBrush = new SolidBrush(Color.Black);
private void Form1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.Clear();
e.Graphics.FillEllipse(myBrush, 0, 0, this.ClientSize.Width, this.ClientSize.Height);
}

How to make a UserControls BackColor transparent in C#?

I created a simple stick man in a Windows Form User-Control (consisting of a radio button and three labels and one progress bar).
I set the back-color of the new user-control to transparent so that when I drag it onto my form, it blends with other colors and drawings on the form.
I am not getting what I'm trying to achieve.
Here is the picture:
UserControl already supports this, its ControlStyles.SupportsTransparentBackColor style flag is already turned on. All you have to do is set the BackColor property to Color.Transparent.
Next thing you have to keep in mind in that this transparency is simulated, it is done by asking the Parent of the control to draw itself to produce the background. So what is important is that you get the Parent set correctly. That's a bit tricky to do if the parent is not a container control. Like a PictureBox. The designer will make the Form the parent so you will see the form's background, not the picture box. You'll need to fix that in code, edit the form constructor and make it look similar to this:
var pos = this.PointToScreen(userControl11.Location);
userControl11.Parent = pictureBox1;
userControl11.Location = pictureBox1.PointToClient(pos);
In constructor set style of control to support a transparent backcolor
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
and then set Background to transperent color
this.BackColor = Color.Transparent;
From MSDN
A more complex approach (and possibly working one) is described here - with overrding of CreateParams and OnPaint.
Why all those things?
UserControl class has property Region.
Set this to what ever shape you like and no other adjustments are needed.
public partial class TranspBackground : UserControl
{
public TranspBackground()
{
InitializeComponent();
}
GraphicsPath GrPath
{
get
{
GraphicsPath grPath = new GraphicsPath();
grPath.AddEllipse(this.ClientRectangle);
return grPath;
}
}
protected override void OnPaint(PaintEventArgs e)
{
// set the region property to the desired path like this
this.Region = new System.Drawing.Region(GrPath);
// other drawing goes here
e.Graphics.FillEllipse(new SolidBrush(ForeColor), ClientRectangle);
}
}
The result is as in the image below:
No low level code, no tweaking, simple and clean.
There is however one issue but in most cases it can go undetected, the edges are not smooth and anti-aliasing will not help either.
But the workaround is fairly easy. In fact much easier than all those complex background handling..

Categories

Resources