Search code examples
c#.netwinformspaintinvalidation

C# Invalidate is not calling paint method


I have OnPaint method overrided to draw an Ellipse on the screen.

    protected override void OnPaint(PaintEventArgs e)
    {
        MessageBox.Show("Paint");
        if (debugStarted)
        {
            int y = rtbLogicCode.PlaceToPoint(new Place(0, debugLine)).Y;
            if (rtbLogicCode.GetVisibleState(debugLine).ToString() == "Visible")
            {
                e.Graphics.FillEllipse(new LinearGradientBrush(new Rectangle(0, y, 15, 15), Color.LightPink, Color.Red, 45), 0, y, 15, 15);
            }
            base.OnPaint(e);
        }
    }

    private void rtbLogicCode_Scroll(object sender, ScrollEventArgs e)
    {
        this.Invalidate();
    }

The scroll event (On the Richtextbox) is handled properly but even though I am invalidating the form, it isn't calling the OnPaint function (The messagebox isn't showing).

What could be the possible cause of this?

Edit: I have forgot to mention that on my initialization function of the child form (added as a control of the main form using MDI property), I set the following styles:

 private void LogicCodeInit()
    {


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


    }

Edit2: I've also forgot to mention that the child form is added as a control of TabControl. The TabControl then is added as a control of the main form.


Solution

  • Call Update after Invalidate. Invalidate repaints the form only if it has focus, it's probably not getting focus since it's being added as a TabControl child.

    From MSDN documentation:

    Calling the Invalidate method does not force a synchronous paint; to force a synchronous paint, call the Update method after calling the Invalidate method. When this method is called with no parameters, the entire client area is added to the update region.