简体   繁体   中英

Drawing does not work after resizing user control with Dock is not None

I have a very simple code to draw a grid on my user control (after calling the base class OnBackgroundPaint):

private void DrawGrid(Graphics g)
        {
            Pen p = new Pen(new HatchBrush(HatchStyle.LargeGrid | HatchStyle.Percent50, Color.LightGray, Color.Transparent), 1);

            for (int i = 0; i < this.Size.Width; i+=50)
            {
                g.DrawLine(p, new Point(i, this.Location.Y), new Point(i, this.Size.Height));
            }

            for (int i = 0; i < this.Size.Height; i += 50)
            {
                g.DrawLine(p, new Point(this.Location.X,i), new Point(this.Size.Width, i));
            }
            p.Dispose();
        }

When I place this control to the main form and do not use docking, it works well with resizing. However, when I set the Dock property to anything else than None, after resizing the drawn areas are erased and never drawn again. What could be the reason?

this is becuse you must start from 0, 0 location when you create user control and you want to drow on it you must start from 0, 0 top left location not reallocation of user control on parent

private void DrawGrid(Graphics g)
    {
        Pen p = new Pen(new HatchBrush(HatchStyle.LargeGrid | HatchStyle.Percent50, Color.LightGray, Color.Transparent), 1);

        for (int i = 0; i < this.Size.Width; i+=50)
        {
            g.DrawLine(p, new Point(i, **0**), new Point(i, this.Size.Height));
        }

        for (int i = 0; i < this.Size.Height; i += 50)
        {
            g.DrawLine(p, new Point(**0**,i), new Point(this.Size.Width, i));
        }
        p.Dispose();
    }

also you must call this function in your control constructor :

this.SetStyle(ControlStyles.DoubleBuffer | 
    ControlStyles.UserPaint | 
    ControlStyles.AllPaintingInWmPaint,
    true);
this.UpdateStyles();

this calling tell to user control drawing is performed in a buffer, and after it completes, the result is output to the screen. Double-buffering prevents flicker caused by the redrawing of the control. If you set DoubleBuffer to true, you should also set UserPaint and AllPaintingInWmPaint to true., the control paints itself rather than the operating system doing so. If false, the Paint event is not raised. This style only applies to classes derived from Control. and the control ignores the window message WM_ERASEBKGND to reduce flicker. This style should only be applied if the UserPaint bit is set to true.

for more info you can see this link :

https://msdn.microsoft.com/en-us/library/system.windows.forms.controlstyles(v=vs.110).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM