Handle button messages


   

/*
C#: The Complete Reference 
by Herbert Schildt 

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Handle button messages. 
 
using System; 
using System.Windows.Forms; 
using System.Drawing; 
 
public class ButtonForm1 : Form { 
  Button MyButton = new Button(); 
 
  public ButtonForm1() { 
    Text = "Respond to a Button"; 
 
    MyButton = new Button(); 
    MyButton.Text = "Press Here"; 
    MyButton.Location = new Point(100, 200); 
 
    // Add button event handler to list. 
    MyButton.Click += new EventHandler(MyButtonClick); 
 
    Controls.Add(MyButton); 
  }   
 
  [STAThread] 
  public static void Main() { 
    ButtonForm1 skel = new ButtonForm1(); 
 
    Application.Run(skel); 
  } 
 
  // Handler for MyButton. 
  protected void MyButtonClick(object who, EventArgs e) { 
 
    if(MyButton.Top == 200) 
      MyButton.Location = new Point(10, 10); 
    else 
      MyButton.Location = new Point(100, 200); 
  } 
}


           
          


Add button to form


   

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/

using System;
using System.Windows.Forms;

namespace Form
{
    public class ButtonclsForm : System.Windows.Forms.Form
    {
        private Button button1;
        public ButtonclsForm()
        {
            Text = "A Simple Form";
            button1 = new Button ();
//            SuspendLayout();
            button1.Text = "Cancel";
            button1.Name = "button1";
            button1.Size = new System.Drawing.Size (72, 30);
            button1.Location = new System.Drawing.Point ((ClientRectangle.Width - button1.Size.Width) / 2, ClientRectangle.Height - 35);
            Controls.AddRange(new System.Windows.Forms.Control[] {this.button1});
            button1.Click += new System.EventHandler(OnClickButton1);
//            ResumeLayout (false);
        }
        static public void Main() 
        {
            Application.Run(new ButtonclsForm());
        }
        void OnClickButton1 (object sender, System.EventArgs e)
        {
            Application.Exit ();
        }
    }
}


           
          


Button click action

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace AddControls
{
///

/// Summary description for FormAddControls.
///

public class FormAddControls : System.Windows.Forms.Form
{
private System.Windows.Forms.ListBox listBox1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button button2;
///

/// Required designer variable.
///

private System.ComponentModel.Container components = null;

public FormAddControls()
{
//
// 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.textBox1 = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.listBox1 = new System.Windows.Forms.ListBox();
this.SuspendLayout();
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(38, 200);
this.textBox1.Name = “textBox1”;
this.textBox1.Size = new System.Drawing.Size(216, 20);
this.textBox1.TabIndex = 1;
this.textBox1.Text = “”;
//
// button1
//
this.button1.Location = new System.Drawing.Point(48, 240);
this.button1.Name = “button1”;
this.button1.Size = new System.Drawing.Size(80, 24);
this.button1.TabIndex = 2;
this.button1.Text = “Add Item”;
this.button1.Click += new System.EventHandler(this.button1_Click);
this.button1.MouseEnter += new System.EventHandler(this.Buttons_OnMouseEnter);
this.button1.MouseLeave += new System.EventHandler(this.Buttons_OnMouseLeave);
//
// button2
//
this.button2.Location = new System.Drawing.Point(160, 240);
this.button2.Name = “button2”;
this.button2.Size = new System.Drawing.Size(96, 24);
this.button2.TabIndex = 3;
this.button2.Text = “Cancel”;
this.button2.Click += new System.EventHandler(this.button2_Click);
this.button2.MouseEnter += new System.EventHandler(this.Buttons_OnMouseEnter);
this.button2.MouseLeave += new System.EventHandler(this.Buttons_OnMouseLeave);
//
// listBox1
//
this.listBox1.Location = new System.Drawing.Point(38, 32);
this.listBox1.Name = “listBox1”;
this.listBox1.Size = new System.Drawing.Size(216, 147);
this.listBox1.TabIndex = 0;
//
// FormAddControls
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 273);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.button2,
this.button1,
this.textBox1,
this.listBox1});
this.Name = “FormAddControls”;
this.Text = “FormAddControls”;
this.ResumeLayout(false);

}
#endregion

///

/// The main entry point for the application.
///

[STAThread]
static void Main()
{
Application.Run(new FormAddControls());
}

private void button1_Click(object sender, System.EventArgs e)
{
if (textBox1.Text == “”)
return;
string strAdd = textBox1.Text;
if (listBox1.FindString (strAdd, -1) < 0) { listBox1.Items.Add (strAdd); textBox1.Text = ""; textBox1.Focus (); return; } MessageBox.Show (""" + strAdd + "" is already in the list box", "Duplicate"); } private void button2_Click(object sender, System.EventArgs e) { Application.Exit(); } private void Buttons_OnMouseEnter(object sender, System.EventArgs e) { Button btn = (Button) sender; btn.BackColor = Color.LightGray; } private void Buttons_OnMouseLeave(object sender, System.EventArgs e) { Button btn = (Button) sender; btn.BackColor = SystemColors.Control; } } } [/csharp]

Picture Button



   

/*
Professional Windows GUI Programming Using C#
by Jay Glynn, Csaba Torok, Richard Conway, Wahid Choudhury, 
   Zach Greenvoss, Shripad Kulkarni, Neil Whitlow

Publisher: Peer Information
ISBN: 1861007663
*/

namespace MyButton
{
  using System.Runtime.InteropServices ;
  using System;
  using System.Windows.Forms;
  using System.Drawing;

  /// <summary>
  ///    Summary description for SMKPictureButton
  /// </summary>

  
  public class SMKPictureButton : System.Windows.Forms.ButtonBase
  {
    // Import the CreateRoundRectRgn function from the GDI32.DLL 
    // From the Unmanaged Code
    [DllImport("GDI32.DLL",EntryPoint="CreateRoundRectRgn")]
    private static extern int CreateRoundRectRgn(int x1 , int y1 ,int x2 , int y2 , int x3 , int y3);

    // Import the CreateRectRgn function from the GDI32.DLL 
    // From the Unmanaged Code
    [DllImport("GDI32.DLL",EntryPoint="CreateRectRgn")]
    private static extern int CreateRectRgn(int x1 , int y1 ,int x2 , int y2 );

    // Import the SetWindowRgn function from the user32.DLL
    // From the Unmanaged Code
    [DllImport("user32.DLL",EntryPoint="SetWindowRgn")]
    private static extern int SetWindowRgn( int hWnd , int hRgn , int bRedraw ) ;


    Font f1 = new System.Drawing.Font("System", 10.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
    Font f2 = new System.Drawing.Font("Microsoft Sans Serif", 10.25F, System.Drawing.FontStyle.Italic|System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
    Font f3 = new System.Drawing.Font("Courier", 10F, System.Drawing.FontStyle.Regular|System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
    
    int rg ;
    int hdl ;

    public SMKPictureButton()
    {
    }

    protected override void OnMouseDown ( MouseEventArgs mevent)
    {
      // Override the MouseDown function to set a new image
      // Display Image No 1 from ButtonImageList when mouse is clicked on the button
      ImageIndex = 1;
      Text = "SMILING FACE (MOUSE DOWN)" ;
      Font = f1 ;
      Invalidate();
    }
    
    protected override void OnMouseLeave (EventArgs e)
    {
      // Override the MouseLeave function to set a new image
      // Display Image No 2 from ButtonImageList when mouse leaves the button
      ImageIndex = 2;
      Text = "HAPPY FACE (MOUSE LEAVE)" ;
      Font = f2 ;
      Invalidate();
    }

    protected override void OnMouseEnter(EventArgs e)
    {
      // Override the MouseEnter function to set a new image
      // Display Image No 0 from ButtonImageList when mouse enters the button area
      ImageIndex = 0;
      Text = "SAD FACE (MOUSE ENTER)" ;
      Font = f3 ;
      Invalidate();
    }

    public void Init()
    {
      // Get the dimension of the client rectangle 
      Rectangle rect = this.ClientRectangle  ;  
      // Invoke the unmanaged DLL function here to create the RoundRectangleRegion
      rg = CreateRoundRectRgn(rect.Left+10,rect.Top+10,rect.Right,rect.Bottom,50,50);
      // Get the handle to the window. 
      hdl = this.Handle.ToInt32() ;
      // Set the Window Region to a a Rectangle with rounded corners
      SetWindowRgn( hdl , rg , 1 ) ;
    }

    protected override void OnPaint(PaintEventArgs e)
    {
      // Override this function, since we do not want the control
      // to paint the button. We want to do all the painting ourselves

      // Get the Graphics Object ( .aka. the CDC or the Device Context Object ) 
      Graphics g = e.Graphics;

      // Get the Bounding Rectnalge for the button
      Rectangle rect = e.ClipRectangle;

      // Paint the rectangle with the color you want
      g.FillRectangle(new SolidBrush(Color.LightYellow),rect);

      rect.Inflate(5,5);

      // Define a StringFormat Object to display the string in your custom format
      StringFormat sf = new StringFormat();
      sf.Alignment = StringAlignment.Center ; 
      sf.LineAlignment = StringAlignment.Center ; 

      // Get the current Image that we have set depending on the location of 
      // mouse on the contol.  Refer to the OnMouseDown,OnMouseEnter,OnMouseLeave events
      if ( ImageIndex >= 0 )  
      {
        Image ig = this.ImageList.Images[ImageIndex];

        // Initialize the rectangle where you want the Image
        Rectangle rimg = rect ;
        rimg.X+=rect.Right/2 - 16 ;
        rimg.Y+= rect.Bottom-90 ;
        rimg.Width = 32 ;
        rimg.Height = 32 ; 

        // Draw the Image
        g.DrawImage(ig , rimg, 0,0,32,32 , GraphicsUnit.Pixel);
      }
      
      // Draw the String in the rectngle region you want
      rect.Y = rect.Bottom - 75 ;
      g.DrawString(Text , Font , new SolidBrush(Color.Blue),rect, sf );
    }
  }
}

//========================================================================
//========================================================================


using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace MyButton
{
  /// <summary>
  /// Summary description for Form1.
  /// </summary>
  public class Form1 : System.Windows.Forms.Form
  {
//    private System.Windows.Forms.Button button1;
    private SMKPictureButton button1 ; 
    private System.Windows.Forms.ImageList ButtonImageList;
    private System.Windows.Forms.Label label1;
    private System.ComponentModel.IContainer components;

    public Form1()
    {
      //
      // Required for Windows Form Designer support
      //
      InitializeComponent();

      //
      // TODO: Add any constructor code after InitializeComponent call
      //
    }

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    protected override void Dispose( bool disposing )
    {
      if( disposing )
      {
        if (components != null) 
        {
          components.Dispose();
        }
      }
      base.Dispose( disposing );
    }

    #region Windows Form Designer generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
      this.components = new System.ComponentModel.Container();
      System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1));
      this.ButtonImageList = new System.Windows.Forms.ImageList(this.components);
      this.button1 = new MyButton.SMKPictureButton();
      this.label1 = new System.Windows.Forms.Label();
      this.SuspendLayout();
      // 
      // ButtonImageList
      // 
      this.ButtonImageList.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit;
      this.ButtonImageList.ImageSize = new System.Drawing.Size(32, 32);
      this.ButtonImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("ButtonImageList.ImageStream")));
      this.ButtonImageList.TransparentColor = System.Drawing.Color.Transparent;
      // 
      // button1
      // 
      this.button1.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(255)), ((System.Byte)(192)));
      this.button1.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
      this.button1.ImageAlign = System.Drawing.ContentAlignment.TopCenter;
      this.button1.ImageList = this.ButtonImageList;
      this.button1.Location = new System.Drawing.Point(24, 32);
      this.button1.Name = "button1";
      this.button1.Size = new System.Drawing.Size(296, 104);
      this.button1.TabIndex = 0;
      this.button1.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
      // 
      // label1
      // 
      this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
      this.label1.Location = new System.Drawing.Point(32, 0);
      this.label1.Name = "label1";
      this.label1.Size = new System.Drawing.Size(280, 23);
      this.label1.TabIndex = 1;
      this.label1.Text = "Buttons with Rounded Edges";
      this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
      // 
      // Form1
      // 
      this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      this.ClientSize = new System.Drawing.Size(344, 149);
      this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                      this.label1,
                                      this.button1});
      this.Name = "Form1";
      this.Text = "Button Control";
      this.Load += new System.EventHandler(this.Form1_Load);
      this.ResumeLayout(false);

    }
    #endregion

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main() 
    {
      Application.Run(new Form1());
    }

    private void Form1_Load(object sender, System.EventArgs e)
    {
      // Call the Buttons Init function here.
      // This is where the Rounded Rectangle Region is created
      // and the window is set to as this region
      button1.Init();
    }
  }
}




           
          


Button.zip( 50 k)

Button Action Demo


   

using System;
using System.Drawing;
using System.Windows.Forms;

public class ButtonActionDemo : Form {
    Label label1  = new Label();
    TextBox textBox1 = new TextBox();
    Button button1 = new Button();
    Label label2 = new Label();
    
    public ButtonActionDemo() {
      label1.Location = new Point(56, 48);
      label1.Name = "label1";
      label1.TabIndex = 0;
      label1.Text = "Enter Ur Name : ";
    
      textBox1.Location = new Point(176, 48);
      textBox1.Name = "textBox1";
      textBox1.Size = new Size(112, 20);
      textBox1.Text = "";
    
      button1.Location = new Point(128, 104);
      button1.Name = "button1";
      button1.Text = "Click Me";
    
      label2.Location = new Point(88, 192);
      label2.Name = "label2";
    
      button1.Click += new System.EventHandler(button1_Click1a);
    
      //Controls.AddRange(new Control[]
      //{label2, button1, textBox1, label1});
      //Instead of this u can use the Following
    
      Controls.Add(label2);
      Controls.Add(label1);
      Controls.Add(button1);
      Controls.Add(textBox1);
    }
    static void Main()
    {
      Application.Run(new ButtonActionDemo());
    }
    private void button1_Click1a(object sender, System.EventArgs e)
    {
      label2.Text = "Thanks a Lot ";
    }
}           
          


Hot Track Button Host


   

/*
User Interfaces in C#: Windows Forms and Custom Controls
by Matthew MacDonald

Publisher: Apress
ISBN: 1590590457
*/
using System.ComponentModel;
using System.Drawing;

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace HotTrackButtonHost
{
    /// <summary>
    /// Summary description for HotTrackButtonHost.
    /// </summary>
    public class HotTrackButtonHost : System.Windows.Forms.Form
    {
        private HotTrackButton hotTrackButton1;
        internal HotTrackButton hotTrackButton2;
        internal HotTrackButton HotTrackButton3;
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.Container components = null;

        public HotTrackButtonHost()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null) 
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
//            System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(HotTrackButtonHost));
            this.hotTrackButton1 = new HotTrackButton();
            this.hotTrackButton2 = new HotTrackButton();
            this.HotTrackButton3 = new HotTrackButton();
            this.SuspendLayout();
            // 
            // hotTrackButton1
            // 
//            this.hotTrackButton1.Image = ((System.Drawing.Bitmap)(resources.GetObject("hotTrackButton1.Image")));
            this.hotTrackButton1.Location = new System.Drawing.Point(28, 128);
            this.hotTrackButton1.Name = "hotTrackButton1";
            this.hotTrackButton1.Size = new System.Drawing.Size(168, 36);
            this.hotTrackButton1.TabIndex = 0;
            this.hotTrackButton1.Text = "Large HotTrackButton";
            // 
            // hotTrackButton2
            // 
            this.hotTrackButton2.BackColor = System.Drawing.SystemColors.Control;
            this.hotTrackButton2.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
            this.hotTrackButton2.ForeColor = System.Drawing.Color.Black;
//            this.hotTrackButton2.Image = ((System.Drawing.Bitmap)(resources.GetObject("hotTrackButton2.Image")));
            this.hotTrackButton2.Location = new System.Drawing.Point(32, 24);
            this.hotTrackButton2.Name = "hotTrackButton2";
            this.hotTrackButton2.Size = new System.Drawing.Size(168, 20);
            this.hotTrackButton2.TabIndex = 1;
            this.hotTrackButton2.Text = "Ordinary HotTrackButton";
            // 
            // HotTrackButton3
            // 
            this.HotTrackButton3.BackColor = System.Drawing.SystemColors.Control;
            this.HotTrackButton3.Enabled = false;
            this.HotTrackButton3.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
            this.HotTrackButton3.ForeColor = System.Drawing.Color.Black;
//            this.HotTrackButton3.Image = ((System.Drawing.Bitmap)(resources.GetObject("HotTrackButton3.Image")));
            this.HotTrackButton3.Location = new System.Drawing.Point(32, 68);
            this.HotTrackButton3.Name = "HotTrackButton3";
            this.HotTrackButton3.Size = new System.Drawing.Size(168, 28);
            this.HotTrackButton3.TabIndex = 3;
            this.HotTrackButton3.Text = "Disabled HotTrackButton";
            // 
            // HotTrackButtonHost
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
            this.ClientSize = new System.Drawing.Size(292, 266);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                          this.HotTrackButton3,
                                                                          this.hotTrackButton2,
                                                                          this.hotTrackButton1});
            this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
            this.Name = "HotTrackButtonHost";
            this.Text = "HotTrackButtonHost";
            this.ResumeLayout(false);

        }
        #endregion

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main() 
        {
            Application.Run(new HotTrackButtonHost());
        }
    }
    /// <summary>
    /// Summary description for HotTrackButton.
    /// </summary>
    public class HotTrackButton : Control
    {
        /// <summary> 
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.Container components = null;

        public HotTrackButton()
        {
            // This call is required by the Windows.Forms Form Designer.
            InitializeComponent();

            // TODO: Add any initialization after the InitForm call

        }

        /// <summary> 
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if(components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        #region Component Designer generated code
        /// <summary> 
        /// Required method for Designer support - do not modify 
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            components = new System.ComponentModel.Container();
        }
        #endregion


        public enum State
        {
            Normal,
            MouseOver,
            Pushed
        }

        private State state = State.Normal;

        private Image image;
        private Rectangle bounds;

        public Image Image
        {
            get
            {
                return image;
            }
            set
            {
                image = value;
                bounds = new Rectangle(0, 0, image.Width + 5, image.Height + 5);
                this.Invalidate();
            }
        }

        // You must override this property to invalidate the display and
        // provide automatic refresh when the property is changed.
        public override string Text
        {
            get
            {
                return base.Text;
            }
            set
            {
                base.Text = value;
                this.Invalidate();
            }
        }
        protected override void OnMouseMove(System.Windows.Forms.MouseEventArgs e)
        {
            base.OnMouseMove(e);

            // Check if the mouse pointer is over the button.
            // If the mouse moves off the button surface, it will be deactivated,
            // even if the button is being held in a pressed position.
            // The code repaints the button only if needed.
            if (bounds.Contains(e.X, e.Y))
            {
                if (state == State.Normal)
                {
                    state = State.MouseOver;
                    this.Invalidate(bounds);
                }
            }
            else
            {
                if (state != State.Normal)
                {
                    state = State.Normal;
                    this.Invalidate(bounds);
                }
            }
        }

        protected override void OnMouseLeave(System.EventArgs e)
        {
            // Reset the button appearance. This will also deactivate the button
            // if it has been pressed but not released.
            // The code repaints the button only if needed.
            if (state != State.Normal)
            {
                state = State.Normal;
                this.Invalidate(bounds);
            }
        }

        protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs e)
        {
            // Change the button to a pushed state, provided the mouse pointer is
            // over the image and the Left mouse button has been clicked 
            if (bounds.Contains(e.X, e.Y) &amp;&amp; 
                (e.Button &amp; MouseButtons.Left) == MouseButtons.Left)
            {
                state = State.Pushed;
                this.Invalidate(bounds);
            }
        }

        protected override void OnMouseUp(System.Windows.Forms.MouseEventArgs e)
        {
            // Change the button to a normal state and repaint if needed.
            if (!((e.Button &amp; MouseButtons.Left) == MouseButtons.Left))
            {
                state = State.Normal;

                if (bounds.Contains(e.X, e.Y))
                {
                    state = State.MouseOver;
                    }
                else
                {
                    state = State.Normal;
                }

                this.Invalidate(bounds);
            }
        }


        protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
        {
            if (image == null)
            {
                // Draw the text without the image.
                e.Graphics.DrawString(this.Text, this.Font,
                    new SolidBrush(this.ForeColor), 10, 0);
            }
            else
            {
                if (!this.Enabled)
                {
                    // Paint the picture in a disabled state.
                    ControlPaint.DrawImageDisabled(e.Graphics, image, 2, 2,
                        this.BackColor);
                }
                else
                {
                    // Paint the image according to the button state.
                    switch (state)
                    {
                        case State.Normal:
                            e.Graphics.DrawImage(image, 2, 2);
                            break;
                        case State.MouseOver:
                            ControlPaint.DrawBorder3D(e.Graphics, bounds, 
                                Border3DStyle.Raised, Border3DSide.All);
                            e.Graphics.DrawImage(image, 2, 2);
                            break;
                        case State.Pushed:
                            ControlPaint.DrawBorder3D(e.Graphics, bounds, 
                                Border3DStyle.Sunken, Border3DSide.All);
                            e.Graphics.DrawImage(image, 3, 3);
                            break;
                    }
                }

                // Paint the caption text next to the image.
                e.Graphics.DrawString(this.Text, this.Font,
                    new SolidBrush(this.ForeColor), bounds.Width + 3,
                    (bounds.Height - this.Font.Height) / 2);
            }

        }

        protected override void OnClick(System.EventArgs e)
        {
            // Only propagate the click to the client if it was detected over the image.
            if (state == State.Pushed)
            {
                base.OnClick(e);
            }
        }


    }

    
}



           
          


Button Generator


   

/*
User Interfaces in C#: Windows Forms and Custom Controls
by Matthew MacDonald

Publisher: Apress
ISBN: 1590590457
*/
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace ButtonGenerator
{
    /// <summary>
    /// Summary description for ButtonGenerator.
    /// </summary>
    public class ButtonGenerator : System.Windows.Forms.Form
    {
        internal System.Windows.Forms.GroupBox GroupBox2;
        internal System.Windows.Forms.GroupBox GroupBox1;
        internal System.Windows.Forms.Label Label1;
        internal System.Windows.Forms.TextBox txtLeft;
        internal System.Windows.Forms.Label Label2;
        internal System.Windows.Forms.Button cmdCreate;
        internal System.Windows.Forms.TextBox txtTop;
        internal System.Windows.Forms.StatusBar status;
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.Container components = null;

        public ButtonGenerator()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null) 
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.GroupBox2 = new System.Windows.Forms.GroupBox();
            this.GroupBox1 = new System.Windows.Forms.GroupBox();
            this.Label1 = new System.Windows.Forms.Label();
            this.txtLeft = new System.Windows.Forms.TextBox();
            this.Label2 = new System.Windows.Forms.Label();
            this.cmdCreate = new System.Windows.Forms.Button();
            this.txtTop = new System.Windows.Forms.TextBox();
            this.status = new System.Windows.Forms.StatusBar();
            this.GroupBox1.SuspendLayout();
            this.SuspendLayout();
            // 
            // GroupBox2
            // 
            this.GroupBox2.Anchor = ((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) 
                | System.Windows.Forms.AnchorStyles.Right);
            this.GroupBox2.Location = new System.Drawing.Point(0, 180);
            this.GroupBox2.Name = "GroupBox2";
            this.GroupBox2.Size = new System.Drawing.Size(368, 4);
            this.GroupBox2.TabIndex = 10;
            this.GroupBox2.TabStop = false;
            // 
            // GroupBox1
            // 
            this.GroupBox1.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                                    this.Label1,
                                                                                    this.txtLeft,
                                                                                    this.Label2,
                                                                                    this.cmdCreate,
                                                                                    this.txtTop});
            this.GroupBox1.Location = new System.Drawing.Point(12, 6);
            this.GroupBox1.Name = "GroupBox1";
            this.GroupBox1.Size = new System.Drawing.Size(168, 128);
            this.GroupBox1.TabIndex = 9;
            this.GroupBox1.TabStop = false;
            // 
            // Label1
            // 
            this.Label1.Location = new System.Drawing.Point(16, 52);
            this.Label1.Name = "Label1";
            this.Label1.Size = new System.Drawing.Size(52, 16);
            this.Label1.TabIndex = 0;
            this.Label1.Text = "Left:";
            // 
            // txtLeft
            // 
            this.txtLeft.Location = new System.Drawing.Point(76, 52);
            this.txtLeft.Name = "txtLeft";
            this.txtLeft.Size = new System.Drawing.Size(68, 21);
            this.txtLeft.TabIndex = 4;
            this.txtLeft.Text = "200";
            // 
            // Label2
            // 
            this.Label2.Location = new System.Drawing.Point(16, 24);
            this.Label2.Name = "Label2";
            this.Label2.Size = new System.Drawing.Size(52, 16);
            this.Label2.TabIndex = 1;
            this.Label2.Text = "Top:";
            // 
            // cmdCreate
            // 
            this.cmdCreate.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.cmdCreate.Location = new System.Drawing.Point(36, 84);
            this.cmdCreate.Name = "cmdCreate";
            this.cmdCreate.Size = new System.Drawing.Size(112, 28);
            this.cmdCreate.TabIndex = 2;
            this.cmdCreate.Text = "Create Button";
            this.cmdCreate.Click += new System.EventHandler(this.cmdCreate_Click);
            // 
            // txtTop
            // 
            this.txtTop.Location = new System.Drawing.Point(76, 24);
            this.txtTop.Name = "txtTop";
            this.txtTop.Size = new System.Drawing.Size(68, 21);
            this.txtTop.TabIndex = 3;
            this.txtTop.Text = "50";
            // 
            // status
            // 
            this.status.Location = new System.Drawing.Point(0, 184);
            this.status.Name = "status";
            this.status.Size = new System.Drawing.Size(372, 22);
            this.status.TabIndex = 8;
            // 
            // ButtonGenerator
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
            this.ClientSize = new System.Drawing.Size(372, 206);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                          this.GroupBox2,
                                                                          this.GroupBox1,
                                                                          this.status});
            this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
            this.Name = "ButtonGenerator";
            this.Text = "Button Generator";
            this.GroupBox1.ResumeLayout(false);
            this.ResumeLayout(false);

        }
        #endregion

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main() 
        {
            Application.Run(new ButtonGenerator());
        }

        private int buttonCount = 0;

        private void cmdCreate_Click(object sender, System.EventArgs e)
        {
            buttonCount++;

            // Create the button.
            Button newButton = new Button();
            newButton.Text = "Button " + buttonCount.ToString();
            newButton.Left = int.Parse(txtLeft.Text);
            newButton.Top = int.Parse(txtTop.Text);

            // Attach the event handler.
            newButton.Click += new EventHandler(ButtonHandler);

            this.Controls.Add(newButton);

        }


        private void ButtonHandler(object sender, System.EventArgs e)
        {
            status.Text = " You clicked ... ";
            status.Text += ((Button)sender).Text;
        }

    }
}