Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

winforms

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?
like image 436
user181813 Avatar asked Apr 13 '10 08:04

user181813


2 Answers

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.

like image 187
NibblyPig Avatar answered Nov 11 '22 18:11

NibblyPig


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
  }
like image 24
Henk Holterman Avatar answered Nov 11 '22 19:11

Henk Holterman