Geeks With Blogs
Shape Without Form He who has a why to live for can bear almost any how

GDI+ Drawing outside the lines
  

 

GDI+ Drawing out side the lines


I would like to present two simple concepts:

  • How to create a Graphics object without using an OnPaint Event and its PaintEventArgs.
  • How to get the coordinates for an existing control and draw on it.



It is possible to override OnPaint events.

Overriding the Form's OnPaint:

 
protected override void OnPaint(PaintEventArgs pe)? 
{
 
}
 

Then you will have to get a reference to the graphics object:

 
Graphics g = pe.Graphics;
 

What if, however, we want to click a button and draw shapes on the form?
Or what if we want to draw around a text box to highlight the work area?
How do we get a PaintEventArg ?

Well, luckily we don't have too.

We have been provided with a constructor method.

 
Graphics g = CreateGraphics();
 

That's it. That's all we have to do to create a Graphics object. Now what do we do with it?

Lets go with my idea above and draw rectangles around controls when they receive focus so the user will know where they are on the form.
As seen below.

Get started:

1. In Visual Studio start a new Win32 app.
2. Add a few controls.
3. Make sure to add the necessary Name Spaces

 
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Drawing.Drawing2D; //This is where the Graphics object comes from)
 

Now lets get the coordinates and draw some boxes:

Add this in your Form's class area after the static void Main() declaration.

 
private void PaintMe( Control controlToPaint)
{
Graphics g = CreateGraphics();
 
//Create a Pen object set color to Yellow and Size to 5
Pen pen = new? Pen (Color.Yellow,5);??? 
Pen pen2 = new Pen (Color.Black,7);
 
// This pen2 will be used to add a border around our first box - so it will?? stand out more.
 
//Get the controls Coordinates
int p1 = controlToPaint.Left;
int p2 = controlToPaint.Top;
 
int p3 = controlToPaint.Width;
 int p4 = controlToPaint.Height;
 
 g.DrawRectangle(pen2,p1,p2,p3,p4);
 
 //Draw the Border first or it will cover the yellow
 g.DrawRectangle(pen,p1,p2,p3,p4);
 // Draw the yellow Box
}
 

What we just did:

Instantiated a Graphics and a Pen object.

The DrawRectangle method needs the X-Coordinate of the Top left starting position of the rectangle.
The Y-Coordinate of upper left of the rectangle,
the Width, and the Height of the rectangle.
To get this we got the left, the top, the width, and the height from the control we passed in respectfully.

Now we have a function that accepts a Control and draws a box around it.

The only thing left is to tie this to an event.
Since we want the control highlighted when the user goes to enter information lets add it to the Enter event.

In Visual Studio go to the Form1.cs[Design] view and right click a control and choose properties.
Click the lightening bolt to get to the events.
Go to the Enter event and type in getPainted, press enter to go to code view. Add the PaintMe call.

 
private void getPainted(object sender,System.EventArgs e)
{
PaintMe((Control)sender);? //Cast the object to a Control
}
 

Or if you don't have Visual Studio make sure to add this to your code: private void InitializeComponent() Section - (Please see full code if this isn't clear.)

 
this.yourControlName.Enter += new System.EventHandler(this.getPainted);
 

Ok, One more thing. We probably want the box to go away when the focus is on to another control.

So create one more function:

 
private void refreshForm(object sender,System.EventArgs e)
{
Form1.ActiveForm.Refresh() ; //Repaint the form and erase our drawings
}
 

Keep in mind that any time the form is repainted (like if you move it)your drawings will go away.
Here that is a good thing for us.
So call this from the Leave event like we did for the Enter.
Or add it yourself:

 
this.yourControlName.Leave += new System.EventHandler(this.refreshForm);
 

Pretty neat huh? This could be used for errors, for showing the next location to go to, show missing information on a form. You get the idea.

Now that you know how to create a Graphics object any time you want too, have fun and play with all the drawing methods.

Have fun.

Complete Source:

 Complete Source:

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
//using System.Data;
//using System.IO;
using System.Drawing.Drawing2D;
namespace GDISample
{
    /// 
    /// Summary description for Form1.
    /// 
    public class Form1 : System.Windows.Forms.Form
    {
 
        private System.Windows.Forms.ComboBox comboBox1;
        private System.Windows.Forms.TextBox textBox2;
        private System.Windows.Forms.ListBox listBox1;
        private System.Windows.Forms.CheckBox checkBox1;
        /// 
        /// Required designer variable.
        /// 
        private System.ComponentModel.Container components = null;
 
        public Form1()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();
 
            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }
 
        /// 
        /// Clean up any resources being used.
        /// 
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null) 
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }
        
 
        #region Windows Form Designer generated code
        /// 
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// 
        private void InitializeComponent()
        {
            this.textBox2 = new System.Windows.Forms.TextBox();
            this.comboBox1 = new System.Windows.Forms.ComboBox();
            this.listBox1 = new System.Windows.Forms.ListBox();
            this.checkBox1 = new System.Windows.Forms.CheckBox();
            this.SuspendLayout();
            // 
            // textBox2
            // 
            this.textBox2.Location = new System.Drawing.Point(16, 32);
            this.textBox2.Multiline = true;
            this.textBox2.Name = "textBox2";
            this.textBox2.Size = new System.Drawing.Size(144, 64);
            this.textBox2.TabIndex = 4;
            this.textBox2.Text = "textBox2";
            
            this.textBox2.Leave += new System.EventHandler(this.refreshForm);
            this.textBox2.Enter += new System.EventHandler(this.getPainted);
            // 
            // comboBox1
            // 
            this.comboBox1.DropDownWidth = 136;
            this.comboBox1.Location = new System.Drawing.Point(176, 32);
            this.comboBox1.Name = "comboBox1";
            this.comboBox1.Size = new System.Drawing.Size(112, 21);
            this.comboBox1.TabIndex = 3;
            this.comboBox1.Text = "comboBox1";
            this.comboBox1.Leave += new System.EventHandler(this.refreshForm);
            this.comboBox1.Enter += new System.EventHandler(this.getPainted);
            // 
            // listBox1
            // 
            this.listBox1.Location = new System.Drawing.Point(16, 112);
            this.listBox1.Name = "listBox1";
            this.listBox1.Size = new System.Drawing.Size(144, 95);
            this.listBox1.TabIndex = 5;
            this.listBox1.Leave += new System.EventHandler(this.refreshForm);
            this.listBox1.Enter += new System.EventHandler(this.getPainted);
            // 
            // checkBox1
            // 
            this.checkBox1.Location = new System.Drawing.Point(184, 72);
            this.checkBox1.Name = "checkBox1";
            this.checkBox1.Size = new System.Drawing.Size(104, 32);
            this.checkBox1.TabIndex = 6;
            this.checkBox1.Text = "checkBox1";
            this.checkBox1.Enter += new System.EventHandler(this.getPainted);
            this.checkBox1.Leave += new System.EventHandler(this.refreshForm);
            // 
            // Form1
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(744, 557);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                          this.checkBox1,
                                                                          this.listBox1,
                                                                          this.textBox2,
                                                                          this.comboBox1});
            this.Name = "Form1";
            this.Text = "Form1";
            this.Enter += new System.EventHandler(this.getPainted);
            this.ResumeLayout(false);
 
        }
        #endregion
 
        /// 
        /// The main entry point for the application.
        /// 
        [STAThread]
        
 
        static void Main() 
        {
            Application.Run(new Form1());
        }
        
        
 
        private void PaintMe( Control controlToPaint)
        {
            //Create A Graphics obj
             Graphics g = CreateGraphics(); 
            //Create a Pen obj set color to RED and Size to 5
            Pen pen = new Pen(Color.Yellow,5);
// This pen will be used to add a border around our other so it will stand out more.
    
            Pen pen2 = new Pen(Color.Black,7);            
            //Get the controls Coordinants
 
            int p1 = controlToPaint.Left;
 
            int p2 = controlToPaint.Top;
                            
            int p3 = controlToPaint.Width;
 
            int p4 = controlToPaint.Height;
/*The DrawRectangle Method requires a Pen,The X-Coordinate of Top Left,The Y-Coordinate of upper left
 
  The Width, The Height)*/
 
            
            g.DrawRectangle(pen2,p1,p2,p3,p4); //Draw the Border first or it will cover the yellow
        
            g.DrawRectangle(pen,p1,p2,p3,p4); // Draw the yellow Box
            
        }        
        
        
        private void getPainted(object sender,System.EventArgs e)
        {
                PaintMe((Control)sender);//Cast the object to a Control
        }
 
        
 
        private void refreshForm(object sender,System.EventArgs e)
        {
                 Form1.ActiveForm.Refresh() ; //Repaint the form and erase our drawings
        }
 
        
        
        } 
        
    }
 
 
 
 
 
 

 

Posted on Thursday, March 9, 2006 6:27 PM C# | Back to top


Comments on this post: GDI+ Example

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © [C.B.W] | Powered by: GeeksWithBlogs.net