Windows Forms 2.0 – Button Control Recipes

Posted by: Suprotim Agarwal , on 5/22/2008, in Category WinForms & WinRT
Views: 20735
Abstract: In this article, we will explore how to perform some common tasks using the Button Control of Windows Forms 2.0
Windows Forms 2.0 – Button Control Recipes
 
How Do I Get Started With the Button Control
 
The System.Windows.Forms.Button control is a simple push button that allows a user to click it to perform an action. The Click event handler is invoked whenever the user clicks a button. A button is one of the most popular ways to enable a user to initiate some action. When the button is clicked, it looks as if it is being pushed in and released.
The Button class derives from an abstract class named ButtonBase. Several other classes, such as Checkboxes and RadioButton also inherit from this base class.
The following code example creates a Button btn1, and adds it to a Form. Alternatively, you can drag the Button from the Toolbox on to the form.
 
// Constructor
public frmButton()
{
InitializeComponent();
CreateMyBtn();
}
 
private void CreateMyBtn()
{
      // Create and initialize a Button.
      Button btn1 = new Button();
 
     // Adjust Size and Location    
btn1.Location = new Point(90,90);
 
btn1.Size = new Size(90, 30);
 
// Assign text
btn1.Text = "Click Me";
 
// Add an event handler
btn1.Click += new EventHandler(btn1_Click);
 
// Add the button to the form.
Controls.Add(btn1);
}       
 
// Event handler code
private void btn1_Click(object sender, System.EventArgs e)
{
 
MessageBox.Show("A demo of creating an Event Handler at runtime");
}
 
How Do I Create A Button with A Circular Shape
 
You need to create a button that has a different shape from the standard rectangular button.
Solution
The System.Drawing namespace, plays an important role in Windows programming. It contains types that help you with drawing of controls. The following code example demonstrates how to create a button that has a different shape from the standard rectangular button. We begin by creating a custom control that inherits from UserControl and then overrides the OnPaint event. We then initialize the user-defined button, including defining location and size, and creating a Click event handler.
public class MyClassBtn : UserControl
{
 
protected override void OnPaint(PaintEventArgs e)
{
Graphics graphics = e.Graphics;
Pen myPen = new Pen(Color.Black);
// Give the button a circlular shape
graphics.DrawEllipse(myPen, 0,0, 100, 50);
// Create string to draw.
String drawString = "Click Me";
 
// Create font and brush.
Font drawFont = new Font("Arial", 16);
SolidBrush drawBrush = new SolidBrush(Color.Black);
 
// Create point for upper-left corner of drawing.
PointF drawPoint = new PointF(9.0F, 14.0F);
 
// Draw string to screen.
e.Graphics.DrawString(drawString, drawFont, drawBrush, drawPoint);
 
myPen.Dispose();
}
}
 
public partial class frmButton : Form
{
public frmButton()
{
InitializeComponent();
...
CreateMyBtn();
}
 
private void CreateMyBtn()
{
// Create and initialize a Button.
            MyClassBtn btn = new MyClassBtn();
 
            // Adjust Size and Location
            btn.Location = new Point(20, 20);
            btn.Size = new Size(105, 55);
 
            // Add an event handler
            btn.Click += new EventHandler(btn_Click);
 
            // Add the button to the form.
            Controls.Add(btn);
}
 
// Event handler code
private void btn_Click(object sender, System.EventArgs e)
{
 
MessageBox.Show("A demo of creating a button at runtime");
}
}
 
 
How Do I Raise A Click Event Programatically
 
You need to raise a click event programmatically.
Solution
A Button’s Click event can be triggered in several ways: by a mouse click, by pressing the Enter key, pressing a space bar, or by pressing the Alt key with an access key.
This example demonstrates how to call a button’s click event programmatically, from within a program. Place two buttons btnRaiseEvent and btnAccept on the form. When the btnRaiseEvent is clicked, the click event for btnAccept is also triggered.
private void btnRaiseEvent_Click(object sender, EventArgs e)
{
MessageBox.Show("Press OK to Raise Event");
 
if (btnRaiseEvent.DialogResult == DialogResult.OK)
{
 
btnAccept.PerformClick(); // Calls the Click Event of btnAccept
}
 
}
 
private void btnAccept_Click(object sender, EventArgs e)
{
MessageBox.Show("Accept Button Clicked");
}
 
 
How Do I Create A Multilined Button
 
You are looking for a simple way to make text on a button run over several lines.
Solution
The following code demonstrates how to create a Multilined button control. We start off by creating a custom control called MultiLineButton which derives from a Button class and overrides the OnMouseUp, OnMouseDown and OnPaint event.
 
private void CreateMultilineButton()
{
MultiLineButton btn = new MultiLineButton();
btn.Location = new Point(30,100);
btn.Size = new Size(60,60);
btn.Text = "This is an example of a multiline button that spans lines";
Controls.Add(btn);
}
 
public class MultiLineButton : Button
{
public MultiLineButton()
{
}
 
protected override void OnMouseUp(System.Windows.Forms.MouseEventArgs e)
{
this.Invalidate();
base.OnMouseUp(e);
}
 
protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs e)
{
this.Invalidate();
base.OnMouseDown(e);
}
 
 
 
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
Graphics graphics = e.Graphics;
 
Pen pen = new System.Drawing.Pen(Color.Firebrick);
 
Rectangle rect = new Rectangle(10, 10, 50, 50);
 
SolidBrush brushFill = new SolidBrush(Color.Firebrick);
 
graphics.FillRectangle(brushFill, 4, 4, 56, 56);
 
Font font = new Font(FontFamily.GenericSansSerif , 9, FontStyle.Bold);
 
graphics.DrawString(this.Text, font, brushFill, rect);
 
graphics.DrawRectangle(pen, 4, 4, 56, 56);
 
base.OnPaint(e);
}
 
}
 
How Do I Create An Array Of Buttons And Add Event Handlers To Them At RunTime
 
You need to create an array of buttons at runtime and add eventhandlers to them.
Solution
The following code example demonstrates how you need to initialize new buttons and set their location property. You can then loop through the buttons using a foreach and add an eventhandler for each button in the loop.
private void btnCreateArray_Click(object sender, EventArgs e)
{
int arrSize = 5;
 
Button[] btnNew = new Button[arrSize];
 
for(int i = 0; i < btnNew.Length; i++)
{
btnNew[i] = new Button();
// Setting the location property
btnNew[i].Location = new Point(172,50 + i * 30);
}
 
Controls.AddRange(btnNew);
 
// Adding an eventhandler
foreach(Button btn in btnNew)
{
btn.Text = "Click Me ";
btn.Click += new EventHandler(b_Click);
 
}
 
}
 
private void b_Click(object sender, EventArgs e)
{
 
}
 
Conclusion :
 
In this article, we saw a recipe approach to performing some of the most common tasks with the Button Control. I hope the article was useful and I thank you for viewing it.
What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by kuhoang on Monday, May 11, 2009 10:46 AM
nice!

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

FREE .NET MAGAZINES

Free DNC .NET Magazine

Tags

JQUERY COOKBOOK

jQuery CookBook