user181813
user181813

Reputation: 1891

Neither Invalidate() nor Refresh() invokes OnPaint()

I'm trying to get from Line #1 to Line #2 in the below code:

using System;  
using System.Windows.Forms;  

namespace MyNameSpace  
{  
    internal class MyTextBox : System.Windows.Forms.TextBox  
    {  
        protected override void OnEnabledChanged(EventArgs e)  
        {  
            base.OnEnabledChanged(e);  
            Invalidate(); // Line #1 - can get here  
            Refresh();  
        }

       protected override void OnPaint(PaintEventArgs e)  
       {
            base.OnPaint(e);   
            System.Diagnostics.Debugger.Break(); // Line #2 - can't get here  
       }  
    }  
}  

However, it seems that neiter Invalidate() nor Refresh() causes OnPaint(PaintEventArgs e) to be invoked. Two questions:

  1. Why doesn't it work?
  2. If it can't be fixed: I only want to invoke OnPaint(PaintEventArgs e) in order to access the e.Graphics object - is there any other way to do this?

Upvotes: 11

Views: 4759

Answers (3)

Henk Holterman
Henk Holterman

Reputation: 273864

Edit: After reading Chris's comment I agree you probably should not use this.


To answer the other part of the question, you can get a graphics object for an arbitrary control with:

 Graphics g = panel1.CreateGraphics();

But when doing that, you are also responsible for cleaning it up so the correct form is:

  using (Graphics g = this.CreateGraphics())
  {
     // all your drawing here
  }

Upvotes: 3

Victor Hurdugaci
Victor Hurdugaci

Reputation: 28435

internal class MyTextBox : System.Windows.Forms.TextBox
{
    public MyTextBox()
    {
        this.SetStyle(ControlStyles.UserPaint, true);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
    }
}

Upvotes: 0

NibblyPig
NibblyPig

Reputation: 52962

To override the drawing of the control, you must set the style to be UserPaint like this:

this.SetStyle(ControlStyles.UserPaint, true);

See this for more information:

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.setstyle.aspx

UserPaint If 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.

Upvotes: 13

Related Questions