Как добавить кнопки в windows forms

Последнее обновление: 31.10.2015

Элементы управления

Последнее обновление: 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, которое управляет позиционированием изображения на кнопке:

ImageAlign

Нам доступны 9 вариантов, с помощью которых мы можем прикрепить изображение к определенной стороне кнопки. Оставим здесь значение по умолчанию — MiddleCenter,
то есть позиционирование по центру.

Затем перейдем к свойству TextImageRelation и установим для него значение ImageBeforeText. В итоге мы получим кнопку,
где сразу после изображения идет надпись на кнопке:

Кнопка с изображением в Windows Forms

Клавиши быстрого доступа

При работе с формами при использовании клавиатуры очень удобно пользоваться клавишами быстрого доступа. При нажатии на клавиатуре комбинации
клавиш At+некоторый символ, будет вызываться определенная кнопка. Например, зададим для некоторой кнопки свойство Text равное &Аватар.
Первый знак — амперсанд — определяет ту букву, которая будет подчеркнута. В данном случае надпись будет выглядеть как
Аватар. И теперь чтобы вызвать событие Click, нам достаточно нажать на комбинацию клавиш Alt+А.

Кнопки по умолчанию

Форма, на которой размещаются все элементы управления, имеет свойства, позволяющие назначать кнопку по умолчанию и кнопку отмены.

Так, свойство формы AcceptButton позволяет назначать кнопку по умолчанию, которая будет срабатывать по нажатию на клавишу Enter.

Аналогично работает свойство формы CancelButton, которое назначает кнопку отмены. Назначив такую кнопку, мы можем вызвать ее нажатие,
нажав на клавишу Esc.

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    A Button is an essential part of an application, or software, or webpage. It allows the user to interact with the application or software. For example, if a user wants to exit from the current application so, he/she click the exit button which closes the application. It can be used to perform many actions like to submit, upload, download, etc. according to the requirement of your program. It can be available with different shape, size, color, etc. and you can reuse them in different applications. In .NET Framework, Button class is used to represent windows button control and it is inherited from ButtonBase class. It is defined under System.Windows.Forms namespace. 
    In C# you can create a button on the windows form by using two different ways:
    1. Design-Time: It is the easiest method to create a button. Use the below steps: 
     

    • Step 1: Create a windows form as shown in the below image: 
      Visual Studio -> File -> New -> Project -> WindowsFormApp 
       

    • Step 2: Drag the Button control from the ToolBox and drop it on the windows form. You are allowed to place a Button control anywhere on the windows form according to your need. 
       

    • Step 3: After drag and drop you will go to the properties of the Button control to set the properties of the Button. 
       

    2. Run-Time: It is a little bit trickier than the above method. In this method, you can create your own Button using the Button class. 
     

    • Step 1: Create a button using the Button() constructor is provided by the Button class.
       
    // Creating Button using Button class
    Button MyButton = new Button();
    • Step 2: After creating 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 Add() method. 
       
    // Add this Button to form
    this.Controls.Add(Mybutton);
    • Example:
       

    CSharp

    using System;

    using System.Collections.Generic;

    using System.ComponentModel;

    using System.Data;

    using System.Drawing;

    using System.Linq;

    using System.Text;

    using System.Threading.Tasks;

    using System.Windows.Forms;

    namespace WindowsFormsApp8 {

    public partial class Form1 : Form {

        public Form1()

        {

            InitializeComponent();

        }

        private void Form1_Load(object sender, EventArgs e)

        {

            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);

            this.Controls.Add(l);

            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);

            this.Controls.Add(Mybutton);

            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);

            this.Controls.Add(Mybutton1);

        }

    }

    }

    • Output: 
       

    Important Properties of Button

    Property Description
    BackColor Using BackColor property you can set the background color of the button.
    BackgroundImage Using BackgroundImage property you can set the background image on the button.
    AutoEllipsis Using AutoEllipsis property you can set a value which 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 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 ForeColor property you can set the foreground color of the button.
    Height Using Height property you can set the height of the button.
    Image Using Image property you can set the image on the button.
    Margin Using Margin property you can set the margin between controls.
    Name Using Name property you can set the name of the button.
    Padding Using Padding property you can set the padding within the button.
    Visible Using Visible property you can set a value which shows whether the button and all its child buttons are displayed.

    Important Events on Button

    Event Description
    Click This event occur when the button is clicked.
    DoubleClick This event occur when the user performs double click on the button.
    Enter This event occur when the control is entered.
    KeyPress This event occur 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 occur when you click the mouse pointer on the button.
    MouseDoubleClick This event occur when you double click the mouse pointer on the button.
    MouseHover This event occur when the mouse pointer placed on the button.
    MouseLeave This event occur when the mouse pointer leaves the button.

    Improve Article

    Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    A Button is an essential part of an application, or software, or webpage. It allows the user to interact with the application or software. For example, if a user wants to exit from the current application so, he/she click the exit button which closes the application. It can be used to perform many actions like to submit, upload, download, etc. according to the requirement of your program. It can be available with different shape, size, color, etc. and you can reuse them in different applications. In .NET Framework, Button class is used to represent windows button control and it is inherited from ButtonBase class. It is defined under System.Windows.Forms namespace. 
    In C# you can create a button on the windows form by using two different ways:
    1. Design-Time: It is the easiest method to create a button. Use the below steps: 
     

    • Step 1: Create a windows form as shown in the below image: 
      Visual Studio -> File -> New -> Project -> WindowsFormApp 
       

    • Step 2: Drag the Button control from the ToolBox and drop it on the windows form. You are allowed to place a Button control anywhere on the windows form according to your need. 
       

    • Step 3: After drag and drop you will go to the properties of the Button control to set the properties of the Button. 
       

    2. Run-Time: It is a little bit trickier than the above method. In this method, you can create your own Button using the Button class. 
     

    • Step 1: Create a button using the Button() constructor is provided by the Button class.
       
    // Creating Button using Button class
    Button MyButton = new Button();
    • Step 2: After creating 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 Add() method. 
       
    // Add this Button to form
    this.Controls.Add(Mybutton);
    • Example:
       

    CSharp

    using System;

    using System.Collections.Generic;

    using System.ComponentModel;

    using System.Data;

    using System.Drawing;

    using System.Linq;

    using System.Text;

    using System.Threading.Tasks;

    using System.Windows.Forms;

    namespace WindowsFormsApp8 {

    public partial class Form1 : Form {

        public Form1()

        {

            InitializeComponent();

        }

        private void Form1_Load(object sender, EventArgs e)

        {

            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);

            this.Controls.Add(l);

            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);

            this.Controls.Add(Mybutton);

            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);

            this.Controls.Add(Mybutton1);

        }

    }

    }

    • Output: 
       

    Important Properties of Button

    Property Description
    BackColor Using BackColor property you can set the background color of the button.
    BackgroundImage Using BackgroundImage property you can set the background image on the button.
    AutoEllipsis Using AutoEllipsis property you can set a value which 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 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 ForeColor property you can set the foreground color of the button.
    Height Using Height property you can set the height of the button.
    Image Using Image property you can set the image on the button.
    Margin Using Margin property you can set the margin between controls.
    Name Using Name property you can set the name of the button.
    Padding Using Padding property you can set the padding within the button.
    Visible Using Visible property you can set a value which shows whether the button and all its child buttons are displayed.

    Important Events on Button

    Event Description
    Click This event occur when the button is clicked.
    DoubleClick This event occur when the user performs double click on the button.
    Enter This event occur when the control is entered.
    KeyPress This event occur 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 occur when you click the mouse pointer on the button.
    MouseDoubleClick This event occur when you double click the mouse pointer on the button.
    MouseHover This event occur when the mouse pointer placed on the button.
    MouseLeave This event occur when the mouse pointer leaves the button.

    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.

    1.   
    2. dynamicButton.Image = Image.FromFile(@«C:ImagesDock.jpg»);  
    3.   
    4. dynamicButton.ImageAlign = ContentAlignment.MiddleRight;  
    5. dynamicButton.TextAlign = ContentAlignment.MiddleLeft;  
    6.   
    7. 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.

    1. dynamicButton.Text = «I am Dynamic Button»;  
    2. dynamicButton.TextAlign = ContentAlignment.MiddleLeft;  
    3. 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.

    1. 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.

    1.   
    2. dynamicButton.Click += new EventHandler(DynamicButton_Click);  

    The signature of Button click event handler is listed in the following code snippet.

    1. private void DynamicButton_Click(object sender, EventArgs e)  
    2. { }  

    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.

    1.   
    2. 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.

    1.   
    2. dynamicButton.Location = new Point(20, 150);  
    3. dynamicButton.Height = 40;  
    4. 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.

    1.   
    2. dynamicButton.BackColor = Color.Red;  
    3. dynamicButton.ForeColor = Color.Blue;  
    4. dynamicButton.Text = «I am Dynamic Button»;  
    5. dynamicButton.Name = «DynamicButton»;  
    6. 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.

    1.   
    2. dynamicButton.Click += new EventHandler(DynamicButton_Click);  

    The signature of Button click event handler is listed in the following code snippet.

    1. private void DynamicButton_Click(object sender, EventArgs e)  
    2. { }  

    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.

    1. 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.

    1.   
    2.   
    3.   
    4.   
    5. private void CreateDynamicButton()  
    6. {  
    7.   
    8.   
    9.    Button dynamicButton = new Button();  
    10.   
    11.   
    12.    dynamicButton.Height = 40;  
    13.    dynamicButton.Width = 300;  
    14.    dynamicButton.BackColor = Color.Red;  
    15.    dynamicButton.ForeColor = Color.Blue;  
    16.    dynamicButton.Location = new Point(20, 150);  
    17.    dynamicButton.Text = «I am Dynamic Button»;  
    18.    dynamicButton.Name = «DynamicButton»;  
    19.    dynamicButton.Font = new Font(«Georgia», 16);  
    20.   
    21.   
    22.    dynamicButton.Click += new EventHandler(DynamicButton_Click);  
    23.   
    24.   
    25.   
    26.    Controls.Add(dynamicButton);  
    27. }  
    28.   
    29.   
    30.   
    31.   
    32.   
    33.   
    34.   
    35. private void DynamicButton_Click(object sender, EventArgs e)  
    36. {  
    37.    MessageBox.Show(«Dynamic button is clicked»);  
    38. }  

    You need to make sure to call CreateDynamicButton() method on the Form’s constructor just after InitializeComponent() method, listed as following.

    1. public Form1()  
    2. {  
    3.    InitializeComponent();  
    4.    CreateDynamicButton();  
    5. }  

    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.

    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.

    1.   
    2. dynamicButton.Image = Image.FromFile(@«C:ImagesDock.jpg»);  
    3.   
    4. dynamicButton.ImageAlign = ContentAlignment.MiddleRight;  
    5. dynamicButton.TextAlign = ContentAlignment.MiddleLeft;  
    6.   
    7. 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.

    1. dynamicButton.Text = «I am Dynamic Button»;  
    2. dynamicButton.TextAlign = ContentAlignment.MiddleLeft;  
    3. 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.

    1. 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.

    1.   
    2. dynamicButton.Click += new EventHandler(DynamicButton_Click);  

    The signature of Button click event handler is listed in the following code snippet.

    1. private void DynamicButton_Click(object sender, EventArgs e)  
    2. { }  

    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.

    1.   
    2. 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.

    1.   
    2. dynamicButton.Location = new Point(20, 150);  
    3. dynamicButton.Height = 40;  
    4. 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.

    1.   
    2. dynamicButton.BackColor = Color.Red;  
    3. dynamicButton.ForeColor = Color.Blue;  
    4. dynamicButton.Text = «I am Dynamic Button»;  
    5. dynamicButton.Name = «DynamicButton»;  
    6. 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.

    1.   
    2. dynamicButton.Click += new EventHandler(DynamicButton_Click);  

    The signature of Button click event handler is listed in the following code snippet.

    1. private void DynamicButton_Click(object sender, EventArgs e)  
    2. { }  

    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.

    1. 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.

    1.   
    2.   
    3.   
    4.   
    5. private void CreateDynamicButton()  
    6. {  
    7.   
    8.   
    9.    Button dynamicButton = new Button();  
    10.   
    11.   
    12.    dynamicButton.Height = 40;  
    13.    dynamicButton.Width = 300;  
    14.    dynamicButton.BackColor = Color.Red;  
    15.    dynamicButton.ForeColor = Color.Blue;  
    16.    dynamicButton.Location = new Point(20, 150);  
    17.    dynamicButton.Text = «I am Dynamic Button»;  
    18.    dynamicButton.Name = «DynamicButton»;  
    19.    dynamicButton.Font = new Font(«Georgia», 16);  
    20.   
    21.   
    22.    dynamicButton.Click += new EventHandler(DynamicButton_Click);  
    23.   
    24.   
    25.   
    26.    Controls.Add(dynamicButton);  
    27. }  
    28.   
    29.   
    30.   
    31.   
    32.   
    33.   
    34.   
    35. private void DynamicButton_Click(object sender, EventArgs e)  
    36. {  
    37.    MessageBox.Show(«Dynamic button is clicked»);  
    38. }  

    You need to make sure to call CreateDynamicButton() method on the Form’s constructor just after InitializeComponent() method, listed as following.

    1. public Form1()  
    2. {  
    3.    InitializeComponent();  
    4.    CreateDynamicButton();  
    5. }  

    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.

    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.

    1.   
    2. dynamicButton.Image = Image.FromFile(@«C:ImagesDock.jpg»);  
    3.   
    4. dynamicButton.ImageAlign = ContentAlignment.MiddleRight;  
    5. dynamicButton.TextAlign = ContentAlignment.MiddleLeft;  
    6.   
    7. 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.

    1. dynamicButton.Text = «I am Dynamic Button»;  
    2. dynamicButton.TextAlign = ContentAlignment.MiddleLeft;  
    3. 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.

    1. 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.

    1.   
    2. dynamicButton.Click += new EventHandler(DynamicButton_Click);  

    The signature of Button click event handler is listed in the following code snippet.

    1. private void DynamicButton_Click(object sender, EventArgs e)  
    2. { }  

    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.

    1.   
    2. 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.

    1.   
    2. dynamicButton.Location = new Point(20, 150);  
    3. dynamicButton.Height = 40;  
    4. 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.

    1.   
    2. dynamicButton.BackColor = Color.Red;  
    3. dynamicButton.ForeColor = Color.Blue;  
    4. dynamicButton.Text = «I am Dynamic Button»;  
    5. dynamicButton.Name = «DynamicButton»;  
    6. 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.

    1.   
    2. dynamicButton.Click += new EventHandler(DynamicButton_Click);  

    The signature of Button click event handler is listed in the following code snippet.

    1. private void DynamicButton_Click(object sender, EventArgs e)  
    2. { }  

    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.

    1. 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.

    1.   
    2.   
    3.   
    4.   
    5. private void CreateDynamicButton()  
    6. {  
    7.   
    8.   
    9.    Button dynamicButton = new Button();  
    10.   
    11.   
    12.    dynamicButton.Height = 40;  
    13.    dynamicButton.Width = 300;  
    14.    dynamicButton.BackColor = Color.Red;  
    15.    dynamicButton.ForeColor = Color.Blue;  
    16.    dynamicButton.Location = new Point(20, 150);  
    17.    dynamicButton.Text = «I am Dynamic Button»;  
    18.    dynamicButton.Name = «DynamicButton»;  
    19.    dynamicButton.Font = new Font(«Georgia», 16);  
    20.   
    21.   
    22.    dynamicButton.Click += new EventHandler(DynamicButton_Click);  
    23.   
    24.   
    25.   
    26.    Controls.Add(dynamicButton);  
    27. }  
    28.   
    29.   
    30.   
    31.   
    32.   
    33.   
    34.   
    35. private void DynamicButton_Click(object sender, EventArgs e)  
    36. {  
    37.    MessageBox.Show(«Dynamic button is clicked»);  
    38. }  

    You need to make sure to call CreateDynamicButton() method on the Form’s constructor just after InitializeComponent() method, listed as following.

    1. public Form1()  
    2. {  
    3.    InitializeComponent();  
    4.    CreateDynamicButton();  
    5. }  

    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.

    Like this post? Please share to your friends:
  • Как добавить кмс активатор в исключения защитника windows 10
  • Как добавить клавиатуру на панель задач windows 10
  • Как добавить китайскую клавиатуру на компьютер windows 10
  • Как добавить китайский язык на windows 10
  • Как добавить кириллицу в windows 10