📌  相关文章
📜  如何在C#中设置GroupBox的前景颜色?

📅  最后修改于: 2021-05-29 21:43:28             🧑  作者: Mango

在Windows窗体中,GroupBox是一个容器,其中包含多个控件,并且这些控件彼此相关。换句话说,GroupBox是带有适当的可选标题的一组控件周围的框架显示。或者使用GroupBox将相关控件分类到一个组中。在GroupBox中,可以使用ForeColor属性在表单中设置GroupBox的前景色。您可以通过两种不同的方式设置此属性:

1.设计时:这是设置GroupBox的前景色的最简单方法,如以下步骤所示:

  • 第1步:创建一个Windows窗体,如下图所示:
    Visual Studio->文件->新建->项目-> WindowsFormApp
  • 步骤2:接下来,将GroupBox从工具箱拖放到窗体,如下图所示:

  • 步骤3:拖放之后,您将转到GroupBox的属性并设置GroupBox的前景色,如下图所示:

    输出:

2.运行时:比上述方法有些棘手。在此方法中,可以借助给定的语法以编程方式设置GroupBox的前景色:

public virtual System.Drawing.Color ForeColor { get; set; }

在这里,颜色表示GroupBox的前景色。以下步骤显示了如何动态设置GroupBox的前景色:

  • 步骤1:使用GroupBox类提供的GroupBox()构造函数创建GroupBox。
    // Creating a GroupBox
    GroupBox gbox = new GroupBox(); 
    
  • 步骤2:创建GroupBox之后,设置GroupBox类提供的GroupBox的ForeColor属性。
    // Setting the foreground color
    gbox.ForeColor = Color.Maroon;
    
  • 步骤3:最后,将此GroupBox控件添加到表单中,并使用以下语句在GroupBox上添加其他控件:
    // Adding groupbox in the form
    this.Controls.Add(gbox);
    
    and 
    
    // Adding this control to the GroupBox
    gbox.Controls.Add(c2);
    

    例子:

    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 WindowsFormsApp45 {
      
    public partial class Form1 : Form {
      
        public Form1()
        {
            InitializeComponent();
        }
      
        private void Form1_Load(object sender, EventArgs e)
        {
            // Creating and setting 
            // properties of the GroupBox
            GroupBox gbox = new GroupBox();
            gbox.Location = new Point(179, 145);
            gbox.Size = new Size(329, 94);
            gbox.Text = "Select Gender";
            gbox.Name = "Mybox";
            gbox.BackColor = Color.LemonChiffon;
            gbox.ForeColor = Color.Maroon;
      
            // Adding groupbox in the form
            this.Controls.Add(gbox);
      
            // Creating and setting 
            // properties of the CheckBox
            CheckBox c1 = new CheckBox();
            c1.Location = new Point(40, 42);
            c1.Size = new Size(49, 20);
            c1.Text = "Male";
      
            // Adding this control
            // to the GroupBox
            gbox.Controls.Add(c1);
      
            // Creating and setting 
            // properties of the CheckBox
            CheckBox c2 = new CheckBox();
            c2.Location = new Point(183, 39);
            c2.Size = new Size(69, 20);
            c2.Text = "Female";
      
            // Adding this control
            // to the GroupBox
            gbox.Controls.Add(c2);
        }
    }
    }
    

    输出: