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 ";
    }
}           
          


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 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]

Add button to form


   

/*
C# Programming Tips &amp; 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 ();
        }
    }
}


           
          


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 a Button


   

/*
C#: The Complete Reference 
by Herbert Schildt 

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Add a Button. 
 
using System; 
using System.Windows.Forms; 
using System.Drawing; 
 
public class ButtonForm : Form { 
  Button MyButton = new Button(); 
 
  public ButtonForm() { 
    Text = "Using a Button"; 
 
    MyButton = new Button(); 
    MyButton.Text = "Press Here"; 
    MyButton.Location = new Point(100, 200); 
 
    Controls.Add(MyButton); 
  }   
 
  [STAThread] 
  public static void Main() { 
    ButtonForm skel = new ButtonForm(); 
 
    Application.Run(skel); 
  } 
}

           
          


Add two action listeners to a button


   

using System;
using System.Windows.Forms;

public class MyForm : Form{

  void btn1_onclick(object sender, EventArgs e)
  {
    Text = "Sender: " + sender.ToString() + " - Event: " + e.ToString();
  }

  void btn1_onclick2(object sender, EventArgs e){
    Console.WriteLine(String.Format("Sender: {0} - Event: {1}", sender.ToString(), e.ToString()));
  }

  public MyForm() {
    Text = "Hello World";

    Button btn1 = new Button();
    btn1.Text = "Click Me";
    this.Controls.Add(btn1);

    btn1.Click += new EventHandler(btn1_onclick);
    btn1.Click += new EventHandler(btn1_onclick2);
  }

  public static void Main()
  {
    Application.Run(new MyForm());
  }

}