📜  如何在C#中设置按钮的边距?

📅  最后修改于: 2021-05-29 19:29:12             🧑  作者: Mango

按钮是应用程序,软件或网页的重要组成部分。它允许用户与应用程序或软件进行交互。在Button中,允许您使用Margin Property设置两个或多个Button控件之间的间距。您可以通过两种不同的方法使用此属性:

1.设计时:设置两个按钮控件之间的边距是最简单的方法。使用以下步骤:

  • 第1步:创建一个Windows窗体,如下图所示:
    Visual Studio->文件->新建->项目-> WindowsFormApp
  • 步骤2:从工具箱中拖动Button控件,并将其放在Windows窗体上。您可以根据需要在Windows窗体上的任意位置放置一个Button控件。
  • 步骤3:拖放之后,您将转到Button控件的属性来设置Button的Margin属性。

    输出:

运行时:比上面的方法有些棘手。在此方法中,可以借助给定的语法以编程方式设置Button的Margin属性:

public System.Windows.Forms.Padding Margin { get; set; }

在此,填充用于表示控件之间的空间。以下步骤用于设置Button的Margin属性:

  • 步骤1:使用Button类提供的Button()构造函数创建一个按钮。
    // Creating Button using Button class
    Button MyButton = new Button();
    
  • 步骤2:创建Button之后,设置Button类提供的Button的Margin属性。
    // Set the margin of the button
    Mybutton.Margin = new Padding(5, 5, 5, 5);
    
  • 步骤3:最后,使用Add()方法将此按钮控件添加到窗体中。
    // Add this Button to form
    this.Controls.Add(Mybutton);
    

    例子:

    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)
        {
      
            // Creating and setting the properties of label
            Label l = new Label();
            l.AutoSize = true;
            l.Text = "Do you want to submit this form?";
            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);
            Mybutton.Margin = new Padding(5, 5, 5, 5);
            // 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);
            Mybutton1.Margin = new Padding(5, 5, 5, 5);
            // Adding this button to form
            this.Controls.Add(Mybutton1);
        }
    }
    }
    

    输出: