Last Updated :
25 Mar, 2025
A Button is an essential part of an application, software, or webpage. .NET Framework, the Button class is used to represent Windows button control and it is inherited from the ButtonBase class. It is defined under System.Windows.Forms namespace.
It allows users to interact with applications. Clicking an exit button closes the app, for example. Buttons enable actions like submitting or downloading, varying in appearance and reusable across programs.
Ways to Create a Button in Windows Forms
There are mainly two ways to create a button in Windows forms which are mentioned below.
- Drag and drop (Design-Time)
- Custom Button (Run-Time)
Drag and drop (Design-Time)
This is the easiest way to create a button in Windows Forms using Visual Studio we just have to open the toolbox and drag and drop the button on the form in the designer and further we can change the appearance of the button using the properties. Follow these steps to create a button.
Step 1: Locate the project in Visual Studio. In this example, we are using the default project name, Form1. Open the form in the editor to modify it further.
In the image, we have two files that are open one Design and there is Form1.cs these two play a major role. We use the Form 1.cs file for the custom logic.
Step 2: Now open a Toolbox go to the view > Toolbox or ctrl + alt + x.
Step 3. Now open the Common Controls section, then drag and drop a button onto the form where you want it to be placed.
Step 4. Now open the properties of the button press right-click on the button and it will open the properties solution explorer now we can change the button name to Click here.
Now we are changing the Text property from button1 to Click Here.
Step 5: We can change the appearance and the behaviour of the button using the properties.
Output:
Custom Button (Run-Time)
In this method we are going to modify the Form1.cs file and add custom code modification in C# to change the appearance of the button according to our requirements. Follow these step by step process.
Step 1: Create a button using the Button() constructor provided by the Button class.
// Creating Button using Button class
Button MyButton = new Button();
Step 2: After creating the Button, set the properties of the Button provided by the Button class.
// Set the location of the button
Mybutton.Location = new Point(225, 198);
// Set text inside the button
Mybutton.Text = «Submit»;
// Set the AutoSize property of the button
Mybutton.AutoSize = true;
// Set the background color of the button
Mybutton.BackColor = Color.LightBlue;
// Set the padding of the button
Mybutton.Padding = new Padding(6);
// Set font of the text present in the button
Mybutton.Font = new Font(«French Script MT», 18);
Step 3: And last add this button control to form using the Add() method.
// Add this Button to form
this.Controls.Add(Mybutton);
Step 4: Now double-click on the button in Design and it will open the Form cs file where code is written in C#. Here the program file is Form 1.cs Now write this code in Form1.cs file
Form1.cs file:
C#
namespace WinFormsApp1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.AutoSize = true; l.Text = "Do you want to submit this project?"; l.Location = new Point(222, 145); l.Font = new Font("French Script MT", 18); // Adding this label to form this.Controls.Add(l); // Creating and setting the properties of Button Button Mybutton = new Button(); Mybutton.Location = new Point(225, 198); Mybutton.Text = "Submit"; Mybutton.AutoSize = true; Mybutton.BackColor = Color.LightBlue; Mybutton.Padding = new Padding(6); Mybutton.Font = new Font("French Script MT", 18); // Adding this button to form this.Controls.Add(Mybutton); // Creating and setting the properties of Button Button Mybutton1 = new Button(); Mybutton1.Location = new Point(360, 198); Mybutton1.Text = "Cancel"; Mybutton1.AutoSize = true; Mybutton1.BackColor = Color.LightPink; Mybutton1.Padding = new Padding(6); Mybutton1.Font = new Font("French Script MT", 18); // Adding this button to form this.Controls.Add(Mybutton1); } private void button1_Click(object sender, EventArgs e) { } } }
Output:
Properties of Button
These are the important properties of the button
| Property | Description |
|---|---|
| BackColor | Using the BackColor property you can set the background color of the button. |
| BackgroundImage | Using the BackgroundImage property you can set the background image on the button. |
| AutoEllipsis | Using the AutoEllipsis property you can set a value shows that whether the ellipsis character (…) appears at the right edge of the control which denotes that the button text extends beyond the specified length of the button. |
| AutoSize | Using AutoSize property you can set a value which shows whether the button resizes based on its contents. |
| Enabled | Using Enabled property you can set a value which shows whether the button can respond to user interaction. |
| Events | Using the Events property you can get the list of the event handlers that are applied on the given button. |
| Font | Using Font property you can set the font of the button. |
| FontHeight | Using FontHeight property you can set the height of the font. |
| ForeColor | Using the ForeColor property you can set the foreground color of the button. |
| Height | Using the Height property you can set the height of the button. |
| Image | Using Image property you can set the image on the button. |
| Margin | Using the Margin property you can set the margin between controls. |
| Name | Using Name property you can set the name of the button. |
| Padding | Using the Padding property you can set the padding within the button. |
| Visible | Using the Visible property you can set a value which shows whether the button and all its child buttons are displayed. |
Events on Button
| Event | Description |
|---|---|
| Click | This event occurs when the button is clicked. |
| DoubleClick | This event occurs when the user performs a double click on the button. |
| Enter | This event occurs when the control is entered. |
| KeyPress | This event occurs when the character, or space, or backspace key is pressed while the control has focus. |
| Leave | This event occur when the input focus leaves the control. |
| MouseClick | This event occurs when you click the mouse pointer on the button. |
| MouseDoubleClick | This event occurs when you double-click the mouse pointer on the button. |
| MouseHover | This event occurs when the mouse pointer is placed on the button. |
| MouseLeave | This event occur when the mouse pointer leaves the button. |
Элементы управления
Последнее обновление: 31.10.2015
Элементы управления представляют собой визуальные классы, которые получают введенные пользователем данные и могут инициировать различные события.
Все элементы управления наследуются от класса Control и поэтому имеют ряд общих свойств:
-
Anchor: Определяет, как элемент будет растягиваться
-
BackColor: Определяет фоновый цвет элемента
-
BackgroundImage: Определяет фоновое изображение элемента
-
ContextMenu: Контекстное меню, которое открывается при нажатии на элемент правой кнопкой мыши.
Задается с помощью элемента ContextMenu -
Cursor: Представляет, как будет отображаться курсор мыши при наведении на элемент
-
Dock: Задает расположение элемента на форме
-
Enabled: Определяет, будет ли доступен элемент для использования. Если это свойство имеет значение False,
то элемент блокируется. -
Font: Устанавливает шрифт текста для элемента
-
ForeColor: Определяет цвет шрифта
-
Location: Определяет координаты верхнего левого угла элемента управления
-
Name: Имя элемента управления
-
Size: Определяет размер элемента
-
Width: ширина элемента
-
Height: высота элемента
-
TabIndex: Определяет порядок обхода элемента по нажатию на клавишу Tab
-
Tag: Позволяет сохранять значение, ассоциированное с этим элементом управления
Кнопка
Наиболее часто используемым элементом управления является кнопка. Обрабатывая событие нажатия кнопки, мы может производить те или иные действия.
При нажатии на кнопку на форме в редакторе Visual Studio мы по умолчанию попадаем в код обработчика события Click,
который будет выполняться при нажатии:
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Hello World");
}
Оформление кнопки
Чтобы управлять внешним отображением кнопки, можно использовать свойство FlatStyle. Оно может принимать следующие значения:
-
Flat — Кнопка имеет плоский вид
-
Popup — Кнопка приобретает объемный вид при наведении на нее указателя, в иных случаях она имеет плоский вид
-
Standard — Кнопка имеет объемный вид (используется по умолчанию)
-
System — Вид кнопки зависит от операционной системы
Изображение на кнопке
Как и для многих элементов управления, для кнопки можно задавать изображение с помощью свойства BackgroundImage.
Однако мы можем также управлять размещением текста и изображения на кнопки.
Для этого надо использовать свойство TextImageRelation. Оно приобретает следующие значения:
-
Overlay: текст накладывается на изображение
-
ImageAboveText: изображение располагается над текстом
-
TextAboveImage: текст располагается над изображением
-
ImageBeforeText: изображение располагается перед текстом
-
TextBeforeImage: текст располагается перед изображением
Например, установим для кнопки изображение. Для этого выберем кнопку и в окне Свойств нажмем на поле Image (не путать с BackgroundImage). Нам откроется диалоговое окно
установи изображения:
В этом окне выберем опцию Local Resource и нажмем на кнопку Import, после чего нам откроется диалоговое окно для выбора файла изображения.
После выбора изображения мы можем установить свойство ImageAlign, которое управляет позиционированием изображения на кнопке:
Нам доступны 9 вариантов, с помощью которых мы можем прикрепить изображение к определенной стороне кнопки. Оставим здесь значение по умолчанию — MiddleCenter,
то есть позиционирование по центру.
Затем перейдем к свойству TextImageRelation и установим для него значение ImageBeforeText. В итоге мы получим кнопку,
где сразу после изображения идет надпись на кнопке:
Клавиши быстрого доступа
При работе с формами при использовании клавиатуры очень удобно пользоваться клавишами быстрого доступа. При нажатии на клавиатуре комбинации
клавиш At+некоторый символ, будет вызываться определенная кнопка. Например, зададим для некоторой кнопки свойство Text равное &Аватар.
Первый знак — амперсанд — определяет ту букву, которая будет подчеркнута. В данном случае надпись будет выглядеть как
Аватар. И теперь чтобы вызвать событие Click, нам достаточно нажать на комбинацию клавиш Alt+А.
Кнопки по умолчанию
Форма, на которой размещаются все элементы управления, имеет свойства, позволяющие назначать кнопку по умолчанию и кнопку отмены.
Так, свойство формы AcceptButton позволяет назначать кнопку по умолчанию, которая будет срабатывать по нажатию на клавишу Enter.
Аналогично работает свойство формы CancelButton, которое назначает кнопку отмены. Назначив такую кнопку, мы можем вызвать ее нажатие,
нажав на клавишу Esc.
C# Button class in .NET Framework class library represents a Windows Forms Button control. A Button control is a child control placed on a Form and used to process click event and can be clicked by a mouse click or by pressing ENTER or ESC keys.
If AutoEllipsis property is true, it adds ellipsis character to a control if text in control does not fit. You may have to set AutoSize to false to see the ellipses character.
Image in Button
The Image property of a Button control is used to set a button background as an image. The Image property needs an Image object. The Image class has a static method called FromFile that takes an image file name with full path and creates an Image object.
You can also align image and text. The ImageAlign and TextAlign properties of Button are used for this purpose.
The following code snippet sets an image as a button background.
- dynamicButton.Image = Image.FromFile(@«C:\Images\Dock.jpg»);
- dynamicButton.ImageAlign = ContentAlignment.MiddleRight;
- dynamicButton.TextAlign = ContentAlignment.MiddleLeft;
- dynamicButton.FlatStyle = FlatStyle.Flat;
Text and Font
The Text property of Button represents the contents of a Button. The TextAlign property if used to align text within a Button that is of type ContentAlignment enumeration.
The Font property is used to set font of a Button.
The following code snippet sets Text and Font properties of a Button control.
- dynamicButton.Text = «I am Dynamic Button»;
- dynamicButton.TextAlign = ContentAlignment.MiddleLeft;
- dynamicButton.Font = new Font(«Georgia», 16);
Button Control States
Button control has five states — Normal, Flat, Inactive, Pushed, and All. ButtonState enumeration represents a button state.
Unfortunately, Windows Forms does not have a straight-forward way to set a button control state but there is a work around.
Windows Forms has a ControlPaint class with some static methods that can be used to draw various controls at runtime. The DrawButton method is used to draw a Button control and the last parameter of this method is ButtonState enumeration.
The following code snippet sets the button state of button1 using ControlPaint class.
- ControlPaint.DrawButton(System.Drawing.Graphics.FromHwnd(button1.Handle), 0, 0, button1.Width, button1.Height, ButtonState.Pushed);
Adding Button Click Event Hander
A Button control is used to process the button click event. We can attach a button click event handler at run-time by setting its Click event to an EventHandler obect. The EventHandler takes a parameter of an event handler. The Click event is attached in the following code snippet.
- dynamicButton.Click += new EventHandler(DynamicButton_Click);
The signature of Button click event handler is listed in the following code snippet.
- private void DynamicButton_Click(object sender, EventArgs e)
- { }
Creating a C# Button Dynamically
Creating a Button control at run-time is merely a work of creating an instance of Button class, set its properties and add Button class to the Form controls.
First step to create a dynamic button is to create an instance of Button class. The following code snippet creates a Button control object.
- Button dynamicButton = new Button();
Next step, you need to set Button class properties. You need to make sure to specify the Location, Width, Height or Size properties. The default location of Button is left top corner of the Form. The Location property takes a Point that specifies the starting position of the Button on a Form. The Size property specifies the size of the control. We can also use Width and Height property instead of Size property. The following code snippet sets Location, Width, and Height properties of a Button control.
- dynamicButton.Location = new Point(20, 150);
- dynamicButton.Height = 40;
- dynamicButton.Width = 300;
In the next step, you may set more properties of the Button control.
The following code snippet sets background color, foreground color, Text, Name, and Font properties of a Button.
- dynamicButton.BackColor = Color.Red;
- dynamicButton.ForeColor = Color.Blue;
- dynamicButton.Text = «I am Dynamic Button»;
- dynamicButton.Name = «DynamicButton»;
- dynamicButton.Font = new Font(«Georgia», 16);
A Button control is used to process the button click event. We can attach a button click event handler at run-time by setting its Click event to an EventHandler obect. The EventHandler takes a parameter of an event handler. The Click event is attached in the following code snippet.
- dynamicButton.Click += new EventHandler(DynamicButton_Click);
The signature of Button click event handler is listed in the following code snippet.
- private void DynamicButton_Click(object sender, EventArgs e)
- { }
Now the last step is adding a Button control to the Form. The Form.Controls.Add method is used to add a control to a Form. The following code snippet adds a Button control to the current Form.
- Controls.Add(dynamicButton);
The complete code is listed in the following code, where CreateDynamicButton methods creates a Button control to a Form at run-time, attaches a click event handler of the button and adds Button control to the Form by calling Form.Controls.Add() method.
- private void CreateDynamicButton()
- {
- Button dynamicButton = new Button();
- dynamicButton.Height = 40;
- dynamicButton.Width = 300;
- dynamicButton.BackColor = Color.Red;
- dynamicButton.ForeColor = Color.Blue;
- dynamicButton.Location = new Point(20, 150);
- dynamicButton.Text = «I am Dynamic Button»;
- dynamicButton.Name = «DynamicButton»;
- dynamicButton.Font = new Font(«Georgia», 16);
- dynamicButton.Click += new EventHandler(DynamicButton_Click);
- Controls.Add(dynamicButton);
- }
- private void DynamicButton_Click(object sender, EventArgs e)
- {
- MessageBox.Show(«Dynamic button is clicked»);
- }
You need to make sure to call CreateDynamicButton() method on the Form’s constructor just after InitializeComponent() method, listed as following.
- public Form1()
- {
- InitializeComponent();
- CreateDynamicButton();
- }
Summary
In this article, we discussed how to create Button control in Windows Forms using C# at design-time as well as at run-time. We also saw how to set a button properties and set the button click event handler.
Содержание
- 1 Add a Button
- 2 Add button to form
- 3 Add image to Button
- 4 Add quotation char to Button text
- 5 Add two action listeners to a button
- 6 Button Action Demo
- 7 Button click action
- 8 Button FlatStyle Styles
- 9 Button Generator
- 10 Button Image, Size, Parent
- 11 Button Localtion
- 12 Button Name, TabIndex, Text
- 13 Change Button text
- 14 Change Standard Button Text Alignment
- 15 Handle button messages
- 16 Hot Track Button Host
- 17 Paint Owner-Draw Buttons
- 18 Picture Button
- 19 Popup button, Flat button and Image button
- 20 Popup Text
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 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 ();
}
}
}
Add image to Button
using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
public class Form1 : Form
{
private System.Windows.Forms.Button button1;
public Form1() {
InitializeComponent();
}
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
this.button1.Image = new Bitmap("winter.jpg");
this.button1.ImageAlign = System.Drawing.ContentAlignment.TopRight;
this.button1.Location = new System.Drawing.Point(12, 99);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(132, 74);
this.button1.TabIndex = 1;
this.button1.Text = "button1";
this.button1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.button1.UseVisualStyleBackColor = true;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(299, 271);
this.Controls.Add(this.button1);
this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Name = "ImagesInCommonControls";
this.Text = "ImagesInCommonControls";
this.ResumeLayout(false);
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
}
Add quotation char to Button text
using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
public class Form1 : Form
{
[DllImport("User32.dll")]
private static extern short GetAsyncKeyState( System.Windows.Forms.Keys vKey);
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Label lbl;
private System.Windows.Forms.Button cmdAsyncState;
public Form1() {
InitializeComponent();
}
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
lbl.Text = "Key Down: " + e.KeyValue.ToString();
lbl.Text += "\nKey Code: " + e.KeyCode.ToString();
lbl.Text += "\nKey Data: " + e.KeyData.ToString();
if ((e.Modifiers & Keys.Shift) == Keys.Shift)
{
lbl.Text += "\n" + "Shift was held down.";
}
if ((e.Modifiers & Keys.Control) == Keys.Control)
{
lbl.Text += "\n" + "Control was held down.";
}
if (e.Alt)
{
lbl.Text += "\n" + "Alt was held down.";
}
}
private void cmdAsyncState_Click(object sender, EventArgs e)
{
int state = Convert.ToInt32(GetAsyncKeyState(Keys.A).ToString());
switch (state)
{
case 0:
lbl.Text = "A has not been pressed since the last call.";
break;
case 1:
lbl.Text = "A is not currently pressed, but has been pressed since the last call.";
break;
case -32767:
lbl.Text = "A is currently pressed.";
break;
}
}
private void InitializeComponent()
{
this.textBox1 = new System.Windows.Forms.TextBox();
this.lbl = new System.Windows.Forms.Label();
this.cmdAsyncState = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(36, 36);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(205, 21);
this.textBox1.TabIndex = 0;
this.textBox1.Text = "<Text will never appear here>";
//
// lbl
//
this.lbl.AutoSize = true;
this.lbl.Location = new System.Drawing.Point(35, 77);
this.lbl.Name = "lbl";
this.lbl.Size = new System.Drawing.Size(0, 0);
this.lbl.TabIndex = 1;
//
// cmdAsyncState
//
this.cmdAsyncState.Location = new System.Drawing.Point(36, 202);
this.cmdAsyncState.Name = "cmdAsyncState";
this.cmdAsyncState.Size = new System.Drawing.Size(141, 24);
this.cmdAsyncState.TabIndex = 2;
this.cmdAsyncState.Text = "GetAsyncState() for \"A\"";
this.cmdAsyncState.Click += new System.EventHandler(this.cmdAsyncState_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.Add(this.cmdAsyncState);
this.Controls.Add(this.lbl);
this.Controls.Add(this.textBox1);
this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.KeyPreview = true;
this.Name = "Form1";
this.Text = "KeyTest";
this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.Form1_KeyPress);
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);
this.ResumeLayout(false);
this.PerformLayout();
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
}
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());
}
}
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 ";
}
}
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.ruponentModel;
using System.Windows.Forms;
using System.Data;
namespace AddControls
{
/// <summary>
/// Summary description for FormAddControls.
/// </summary>
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;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ruponentModel.Container components = null;
public FormAddControls()
{
//
// 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.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
/// <summary>
/// The main entry point for the application.
/// </summary>
[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;
}
}
}
Button FlatStyle Styles
using System;
using System.Drawing;
using System.Windows.Forms;
class ButtonStyles: Form
{
public static void Main()
{
Application.Run(new ButtonStyles());
}
public ButtonStyles()
{
int y = 0;
foreach (FlatStyle fs in Enum.GetValues(typeof(FlatStyle)))
{
Button btn = new Button();
btn.Parent = this;
btn.FlatStyle = fs;
btn.Text = fs.ToString();
btn.Location = new Point(50, y += 50);
}
}
}
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.ruponentModel;
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.ruponentModel.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;
}
}
}
Button Image, Size, Parent
using System;
using System.Drawing;
using System.Windows.Forms;
class BitmapButtons: Form
{
int cxBtn, cyBtn, dxBtn;
Button btnLarger, btnSmaller;
public static void Main()
{
Application.Run(new BitmapButtons());
}
public BitmapButtons()
{
ResizeRedraw = true;
dxBtn = Font.Height;
btnLarger = new Button();
btnLarger.Parent = this;
btnLarger.Image = new Bitmap(GetType(), "LargerButton.bmp") ;
cxBtn = btnLarger.Image.Width + 8;
cyBtn = btnLarger.Image.Height + 8;
btnLarger.Size = new Size(cxBtn, cyBtn);
btnLarger.Click += new EventHandler(ButtonLargerOnClick);
btnSmaller = new Button();
btnSmaller.Parent = this;
btnSmaller.Image = new Bitmap(GetType(), "SmallerButton.bmp");
btnSmaller.Size = new Size(cxBtn, cyBtn);
btnSmaller.Click += new EventHandler(ButtonSmallerOnClick);
OnResize(EventArgs.Empty);
}
protected override void OnResize(EventArgs ea)
{
base.OnResize(ea);
btnLarger.Location = new Point(ClientSize.Width / 2 - cxBtn - dxBtn / 2,
(ClientSize.Height - cyBtn) / 2);
btnSmaller.Location = new Point(ClientSize.Width / 2 + dxBtn / 2,
(ClientSize.Height - cyBtn) / 2);
}
void ButtonLargerOnClick(object obj, EventArgs ea)
{
Left = 50;
Top = 50;
Width = 50;
Height = 50;
}
void ButtonSmallerOnClick(object obj, EventArgs ea)
{
Left = 200;
Top = 200;
Width = 20;
Height = 20;
}
}
Button Localtion
using System;
using System.Drawing;
using System.Windows.Forms;
class SimpleButton: Form
{
public static void Main()
{
Application.Run(new SimpleButton());
}
public SimpleButton()
{
Text = "Simple Button";
Button btn = new Button();
btn.Parent = this;
btn.Text = "Click Me!";
btn.Location = new Point(100, 100);
btn.Click += new EventHandler(ButtonOnClick);
}
void ButtonOnClick(object obj, EventArgs ea)
{
Graphics grfx = CreateGraphics();
Point ptText = Point.Empty;
string str = "Button clicked!";
grfx.DrawString(str, Font, new SolidBrush(ForeColor), ptText);
grfx.Dispose();
}
}
Button Name, TabIndex, Text
using System;
using System.Windows.Forms;
class MainForm : Form
{
private Label label1;
private TextBox textBox1;
private Button button1;
public MainForm()
{
this.label1 = new Label();
this.textBox1 = new TextBox();
this.button1 = new Button();
this.SuspendLayout();
this.label1.Location = new System.Drawing.Point(16, 36);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(128, 16);
this.label1.TabIndex = 0;
this.label1.Text = "Please enter your name:";
this.textBox1.Location = new System.Drawing.Point(152, 32);
this.textBox1.Name = "textBox1";
this.textBox1.TabIndex = 1;
this.textBox1.Text = "";
this.button1.Location = new System.Drawing.Point(109, 80);
this.button1.Name = "button1";
this.button1.TabIndex = 2;
this.button1.Text = "Enter";
this.button1.Click += new System.EventHandler(this.button1_Click);
this.ClientSize = new System.Drawing.Size(292, 126);
this.Controls.Add(this.button1);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.label1);
this.Name = "form1";
this.Text = "Visual C#";
this.ResumeLayout(false);
}
private void button1_Click(object sender, System.EventArgs e)
{
System.Console.WriteLine("User entered: " + textBox1.Text);
MessageBox.Show("Welcome, " + textBox1.Text, "Visual C#");
}
[STAThread]
public static void Main()
{
Application.EnableVisualStyles();
Application.Run(new MainForm());
}
}
Change Button text
using System;
using System.Windows.Forms;
using System.Drawing;
public class PushMe2 : Form {
Button pushMeButton;
public PushMe2() {
pushMeButton = new Button();
pushMeButton.Text = "Push Me";
pushMeButton.Height = 60;
pushMeButton.Width = 80;
pushMeButton.Top = 60;
pushMeButton.Left = 60;
pushMeButton.Click += new EventHandler(ButtonClicked);
this.Controls.Add(pushMeButton);
this.Height = 200;
this.Width = 200;
this.StartPosition = FormStartPosition.CenterScreen;
this.Visible = true;
}
public void ButtonClicked(object source, EventArgs e) {
Button b = (Button)source;
if ( b.Text == "Push Me" ) {
b.Text = "Ouch";
}
else {
b.Text = "Push Me";
}
}
static void Main() {
Application.Run(new PushMe2());
}
}
Change Standard Button Text Alignment
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
public class ButtonForm : System.Windows.Forms.Form
{
private System.Windows.Forms.Button btnImage;
private System.Windows.Forms.Button btnStandard;
private System.Windows.Forms.Button btnPopup;
private System.Windows.Forms.Button btnFlat;
// Hold the current text alignment
ContentAlignment currAlignment = ContentAlignment.MiddleCenter;
int currEnumPos = 0;
public ButtonForm()
{
InitializeComponent();
// Set btnStandard as default accept.
this.AcceptButton = btnStandard;
CenterToScreen();
}
private void InitializeComponent()
{
this.btnStandard = new System.Windows.Forms.Button();
this.btnFlat = new System.Windows.Forms.Button();
this.btnImage = new System.Windows.Forms.Button();
this.btnPopup = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// btnStandard
//
this.btnStandard.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F);
this.btnStandard.ForeColor = System.Drawing.SystemColors.ControlText;
this.btnStandard.Location = new System.Drawing.Point(16, 80);
this.btnStandard.Name = "btnStandard";
this.btnStandard.Size = new System.Drawing.Size(312, 88);
this.btnStandard.TabIndex = 2;
this.btnStandard.Text = "I am a standard button";
this.btnStandard.Click += new System.EventHandler(this.btnStandard_Click);
//
// btnFlat
//
this.btnFlat.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnFlat.ForeColor = System.Drawing.Color.Blue;
this.btnFlat.Location = new System.Drawing.Point(16, 24);
this.btnFlat.Name = "btnFlat";
this.btnFlat.Size = new System.Drawing.Size(152, 32);
this.btnFlat.TabIndex = 0;
this.btnFlat.Text = "I am flat...";
//
// btnImage
//
this.btnImage.Font = new System.Drawing.Font("Microsoft Sans Serif", 20F, System.Drawing.FontStyle.Bold);
this.btnImage.Image = new Bitmap("winter.jpg");
this.btnImage.Location = new System.Drawing.Point(16, 192);
this.btnImage.Name = "btnImage";
this.btnImage.Size = new System.Drawing.Size(312, 72);
this.btnImage.TabIndex = 3;
this.btnImage.Text = "Image Button";
this.btnImage.TextAlign = System.Drawing.ContentAlignment.TopCenter;
//
// btnPopup
//
this.btnPopup.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.btnPopup.ForeColor = System.Drawing.SystemColors.ControlText;
this.btnPopup.Location = new System.Drawing.Point(176, 24);
this.btnPopup.Name = "btnPopup";
this.btnPopup.Size = new System.Drawing.Size(152, 32);
this.btnPopup.TabIndex = 1;
this.btnPopup.Text = "I am a Popup!";
//
// ButtonForm
//
this.AcceptButton = this.btnStandard;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(340, 269);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.btnImage,
this.btnStandard,
this.btnPopup,
this.btnFlat});
this.ForeColor = System.Drawing.SystemColors.ActiveCaptionText;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
this.Name = "ButtonForm";
this.Text = "Buttons";
this.ResumeLayout(false);
}
protected void btnStandard_Click (object sender, System.EventArgs e)
{
Array values = Enum.GetValues(currAlignment.GetType());
currEnumPos++;
if(currEnumPos >= values.Length)
currEnumPos = 0;
currAlignment = (ContentAlignment)ContentAlignment.Parse(currAlignment.GetType(),
values.GetValue(currEnumPos).ToString());
btnStandard.TextAlign = currAlignment;
btnStandard.Text = currAlignment.ToString();
}
public static void Main(string[] args)
{
Application.Run(new ButtonForm());
}
}
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);
}
}
Hot Track Button Host
/*
User Interfaces in C#: Windows Forms and Custom Controls
by Matthew MacDonald
Publisher: Apress
ISBN: 1590590457
*/
using System.ruponentModel;
using System.Drawing;
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
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.ruponentModel.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.ruponentModel.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.ruponentModel.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) &&
(e.Button & 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 & 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);
}
}
}
}
Paint Owner-Draw Buttons
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
class OwnerDrawButtons: Form
{
readonly int cxImage, cyImage;
readonly int cxBtn, cyBtn, dxBtn;
readonly Button btnLarger, btnSmaller;
public static void Main()
{
Application.Run(new OwnerDrawButtons());
}
public OwnerDrawButtons()
{
ResizeRedraw = true;
cxImage = 4 * Font.Height;
cyImage = 4 * Font.Height;
cxBtn = cxImage + 8;
cyBtn = cyImage + 8;
dxBtn = Font.Height;
btnLarger = new Button();
btnLarger.Parent = this;
btnLarger.Size = new Size(cxBtn, cyBtn);
btnLarger.Click += new EventHandler(ButtonLargerOnClick);
btnLarger.Paint += new PaintEventHandler(ButtonOnPaint);
btnSmaller = new Button();
btnSmaller.Parent = this;
btnSmaller.Size = new Size(cxBtn, cyBtn);
btnSmaller.Click += new EventHandler(ButtonSmallerOnClick);
btnSmaller.Paint += new PaintEventHandler(ButtonOnPaint);
OnResize(EventArgs.Empty);
}
protected override void OnResize(EventArgs ea)
{
base.OnResize(ea);
btnLarger.Location =
new Point(ClientSize.Width / 2 - cxBtn - dxBtn / 2,
(ClientSize.Height - cyBtn) / 2);
btnSmaller.Location =
new Point(ClientSize.Width / 2 + dxBtn / 2,
(ClientSize.Height - cyBtn) / 2);
}
void ButtonLargerOnClick(object obj, EventArgs ea)
{
Console.WriteLine("clicked large");
}
void ButtonSmallerOnClick(object obj, EventArgs ea)
{
Console.WriteLine("clicked small");
}
void ButtonOnPaint(object obj, PaintEventArgs pea)
{
Button btn = (Button) obj;
Graphics grfx = pea.Graphics;
ControlPaint.DrawButton(grfx, 0, 0, cxBtn, cyBtn,
(btn == (Button) GetChildAtPoint(
PointToClient(
MousePosition))) &&
btn.Capture ? ButtonState.Pushed : ButtonState.Normal);
GraphicsState grfxstate = grfx.Save();
grfx.TranslateTransform((cxBtn - cxImage) / 2, (cyBtn - cyImage) / 2);
DrawLargerButton(grfx, cxImage, cyImage);
grfx.Restore(grfxstate);
if (btn.Focused)
ControlPaint.DrawFocusRectangle(grfx,
new Rectangle((cxBtn - cxImage) / 2 + cxImage / 16,
(cyBtn - cyImage) / 2 + cyImage / 16,
7 * cxImage / 8, 7 * cyImage / 8));
}
void DrawLargerButton(Graphics grfx, int cx, int cy)
{
Brush brush = new SolidBrush(btnLarger.ForeColor);
Pen pen = new Pen(btnLarger.ForeColor);
grfx.TranslateTransform(cx / 2, cy / 2);
for (int i = 0; i < 4; i++)
{
grfx.DrawLine(pen, 0, 0, cx / 4, 0);
grfx.FillPolygon(brush, new Point[] {
new Point(cx / 4, -cy / 8),
new Point(cx / 2, 0),
new Point(cx / 4, cy / 8)});
grfx.RotateTransform(90);
}
}
}
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.ruponentModel;
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.ruponentModel.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.ruponents = new System.ruponentModel.Container();
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1));
this.ButtonImageList = new System.Windows.Forms.ImageList(this.ruponents);
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();
}
}
}
<A href=»http://www.nfex.ru/Code/CSharpDownload/Button.zip»>Button.zip( 50 k)</a>
Popup button, Flat button and Image button
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
public class ButtonForm : System.Windows.Forms.Form
{
private System.Windows.Forms.Button btnImage;
private System.Windows.Forms.Button btnStandard;
private System.Windows.Forms.Button btnPopup;
private System.Windows.Forms.Button btnFlat;
// Hold the current text alignment
ContentAlignment currAlignment = ContentAlignment.MiddleCenter;
int currEnumPos = 0;
public ButtonForm()
{
InitializeComponent();
// Set btnStandard as default accept.
this.AcceptButton = btnStandard;
CenterToScreen();
}
private void InitializeComponent()
{
this.btnStandard = new System.Windows.Forms.Button();
this.btnFlat = new System.Windows.Forms.Button();
this.btnImage = new System.Windows.Forms.Button();
this.btnPopup = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// btnStandard
//
this.btnStandard.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F);
this.btnStandard.ForeColor = System.Drawing.SystemColors.ControlText;
this.btnStandard.Location = new System.Drawing.Point(16, 80);
this.btnStandard.Name = "btnStandard";
this.btnStandard.Size = new System.Drawing.Size(312, 88);
this.btnStandard.TabIndex = 2;
this.btnStandard.Text = "I am a standard button";
this.btnStandard.Click += new System.EventHandler(this.btnStandard_Click);
//
// btnFlat
//
this.btnFlat.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnFlat.ForeColor = System.Drawing.Color.Blue;
this.btnFlat.Location = new System.Drawing.Point(16, 24);
this.btnFlat.Name = "btnFlat";
this.btnFlat.Size = new System.Drawing.Size(152, 32);
this.btnFlat.TabIndex = 0;
this.btnFlat.Text = "I am flat...";
//
// btnImage
//
this.btnImage.Font = new System.Drawing.Font("Microsoft Sans Serif", 20F, System.Drawing.FontStyle.Bold);
this.btnImage.Image = new Bitmap("winter.jpg");
this.btnImage.Location = new System.Drawing.Point(16, 192);
this.btnImage.Name = "btnImage";
this.btnImage.Size = new System.Drawing.Size(312, 72);
this.btnImage.TabIndex = 3;
this.btnImage.Text = "Image Button";
this.btnImage.TextAlign = System.Drawing.ContentAlignment.TopCenter;
//
// btnPopup
//
this.btnPopup.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.btnPopup.ForeColor = System.Drawing.SystemColors.ControlText;
this.btnPopup.Location = new System.Drawing.Point(176, 24);
this.btnPopup.Name = "btnPopup";
this.btnPopup.Size = new System.Drawing.Size(152, 32);
this.btnPopup.TabIndex = 1;
this.btnPopup.Text = "I am a Popup!";
//
// ButtonForm
//
this.AcceptButton = this.btnStandard;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(340, 269);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.btnImage,
this.btnStandard,
this.btnPopup,
this.btnFlat});
this.ForeColor = System.Drawing.SystemColors.ActiveCaptionText;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
this.Name = "ButtonForm";
this.Text = "Buttons";
this.ResumeLayout(false);
}
protected void btnStandard_Click (object sender, System.EventArgs e)
{
Array values = Enum.GetValues(currAlignment.GetType());
currEnumPos++;
if(currEnumPos >= values.Length)
currEnumPos = 0;
currAlignment = (ContentAlignment)ContentAlignment.Parse(currAlignment.GetType(),
values.GetValue(currEnumPos).ToString());
btnStandard.TextAlign = currAlignment;
btnStandard.Text = currAlignment.ToString();
}
public static void Main(string[] args)
{
Application.Run(new ButtonForm());
}
}
/*
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.ruponentModel;
using System.Windows.Forms;
using System.Data;
namespace PopupText
{
/// <summary>
/// Summary description for PopupText.
/// </summary>
public class PopupText : System.Windows.Forms.Form
{
internal System.Windows.Forms.Button cmdDelete;
internal System.Windows.Forms.Button cmdAdd;
internal System.Windows.Forms.HelpProvider hlp;
private System.Windows.Forms.Label label1;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ruponentModel.Container components = null;
public PopupText()
{
//
// 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.cmdDelete = new System.Windows.Forms.Button();
this.cmdAdd = new System.Windows.Forms.Button();
this.hlp = new System.Windows.Forms.HelpProvider();
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// cmdDelete
//
this.cmdDelete.Location = new System.Drawing.Point(20, 68);
this.cmdDelete.Name = "cmdDelete";
this.cmdDelete.Size = new System.Drawing.Size(92, 20);
this.cmdDelete.TabIndex = 3;
this.cmdDelete.Text = "Delete";
//
// cmdAdd
//
this.cmdAdd.Location = new System.Drawing.Point(20, 16);
this.cmdAdd.Name = "cmdAdd";
this.cmdAdd.Size = new System.Drawing.Size(92, 20);
this.cmdAdd.TabIndex = 2;
this.cmdAdd.Text = "Add";
//
// label1
//
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.label1.Location = new System.Drawing.Point(48, 176);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(208, 68);
this.label1.TabIndex = 4;
this.label1.Text = "Tab to a button and press F1.";
//
// PopupText
//
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.label1,
this.cmdDelete,
this.cmdAdd});
this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.Name = "PopupText";
this.Text = "PopupText";
this.Load += new System.EventHandler(this.PopupText_Load);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new PopupText());
}
private void PopupText_Load(object sender, System.EventArgs e)
{
hlp.SetHelpString(cmdAdd, "Choose another item from the catalog.");
hlp.SetHelpString(cmdDelete, "Delete the selected item from your order.");
}
}
}
You currently have JavaScript disabled on your web browser.
This website uses JavaScript, and This web page needs JavaScript activated to work correctly.
Please active JavaScript on your web browser and then refresh this web page.
Button
By Tim-Bo Tolbert, posted on Dec 20, 2021
The Button control is found in the System.Windows.Forms namespace within the System.Windows.Forms.dll. In this blog post I am referring to the Button control that is available in C# .NET-Core (.NET 6.0) with Visual Studio 2022 (although this code example might still work OK with older .NET versions).
The purpose and function of a Button control is to provide the user with a measure of interaction capabilities with a program by allowing the user to click on the buttons surface area to trigger a callback click event. The Button control offers additional other events as a means of user interaction as well, other than the click event, but the click event is probably the most used event for this control.
The Button control can be found in the Controls Toolbox window panel within the Forms editor screen. The Button control is a graphical control which takes up some visible space (i.e. real estate) on the form. The position, size and shape of the Button control is variable, and can be set at design time by either through the programs source code or by setting the controls properties using the Form editors property window. The Button controls position, size, shape, and most other properties can also be set and altered at runtime through the programs source code.
A Button control can be clicked by using the mouse, Enter key, or Spacebar, if the button has focus.
To use a button control as a forms Accept or Cancel button, then set the AcceptButton or CancelButton property of the form to allow users to click the button by pressing the Enter (for Accept) or the ESC (for Cencel) keys, even if the button does not have focus. This gives the form the behavior of a dialog box.
When you use the ShowDialog method to display a form, you can specify the return value of that ShowDialog method by setting the DialogResult property of a button on that form.
Example Source Code
This example uses a Button control and a MessageBox object.
To add the Button control to your form, you can double click on its name (i.e. Button) as listed in the Toolbox window panel within the Form editor window. Alternatively, you can single click on it and then drag and drop it onto your form, to position it more closer to where you want it to be positioned at. Once it is added to the form then it will appear on the forms surface area having default button control values.
After you have added the button control to your form then once you select it then you can view and edit that button objects property values in the Properties window within the Forms editor window, where you can then change the buttons Name, Text, and other properties as you desire.
In the example below, I have added a button control object to my form, and then changed the Text property value to «Click Me» :
From the Form editor, double click on the button object that you just added to the Form. Doing so will automatically create and link a callback method to the buttons Click event into that forms .cs source code file, which you can then program some action to be performed whenever the button is clicked.
In the following example, when the program is running and someone clicks on the forms «Click Me» button, then a popup message box will display having the message «Hello» :
namespace TestProgram
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//
}
private void button1_Click(object sender, EventArgs e)
{
// display a popup message box
MessageBox.Show("Hello");
}
}
}
Alternatively, you can also instantiate a new instance of the Button class object as a variable and then add it to the forms control collection manually within the programs source code. If you create and add the button manually within the programs source code instead of by drag and dropping the object in the Form editors window, then you will need to also set all of its properties and callback events manually as well. Below is an example source code of doing just that:
namespace TestProgram
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// instantiate an instance of a new button
Button button1 = new Button();
// add the click event and tie it to a method
button1.Click += Button1_Click;
// set the buttons properties
button1.Name = "button1";
button1.Text = "Click Me";
button1.Left = 20;
button1.Top = 20;
// add the button to the form
this.Controls.Add(button1);
}
// the method to handle the buttons click event
private void Button1_Click(object? sender, EventArgs e)
{
// display a popup message box
MessageBox.Show("Hello");
}
}
}
When you run this example program and click on the «Click Me» button then you should see the following:
Final Thoughts
Thank you for reading, I hope you found this blog post (tutorial) educational and helpful.
This page has been viewed a total of 2136 times.
