標籤:
仿照表單應用程式編寫:
任務一:產生一個Form類的表單對象frm
using System.Windows.Forms; //using指令使用Form對象建立所需的命名空間
//如果using指令不成功,則應該去添加引用,
using System.Drawing;
namespace WindowsFormsApplication6
{
public partial class Form1 : Form //Form是空白表單
{
//Form1繼承於空白表單,又通過建構函式添加新的控制項button等
public Form1() //建構函式
{
InitializeComponent(); //初始化函數
}
private void InitializeComponent() //初始化函數
{
this.textBox1 = new System.Windows.Forms.TextBox(); //建立新的textbox1控制項
this.SuspendLayout(); //掛起控制項更新,使得以後一同更新
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(108, 128); //屬性設定
this.textBox1.Size = new System.Drawing.Size(100, 21);
this.textBox1.TabIndex = 0;
//
this.textBox1.Name = "textBox1";
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 261);
this.Controls.Add(this.textBox1); //添加新產生的控制項textbox1
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
}
static class Program
{
/// <summary>
/// 應用程式的主進入點。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1()); //產生Form1類的對象,並且Application.Run提供一些必要的方法
}
}
}
///////////////////通過觀察上述分析
動態產生表單和添加控制項
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
Form frm = new Form();
// frm.Show(); //這一句可以沒有
// Create a new TextBox control and add it to the form.
TextBox textBox1 = new TextBox();
// Name the control in order to remove it later. The name must be specified
// if a control is added at run time.
textBox1.Name = "textBox1";
// Add the control to the form‘s control collection.
frm.Controls.Add(textBox1);
textBox1.Size = new Size(100, 10);
textBox1.Location = new Point(10, 10);
Application.Run(frm); //這一句務必最後寫
}
}
}
C#構架之基礎學習----動態添加表單和 控制項