C#基础入门二(我的C#学习经历,适合初学者)
#1 五、一个GUI例子
该例子中有一个文本框,两个按钮,单击“点击我”的按钮在文本框中显示“你好,电脑报”。单击“终结者”的按钮结束程序。
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace WindowsApplication1
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
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.textBox1 = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(74, 64);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(144, 21);
this.textBox1.TabIndex = 0;
this.textBox1.Text = "C#酷吗?";
//
// button1
//
this.button1.Location = new System.Drawing.Point(58, 160);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(72, 24);
this.button1.TabIndex = 1;
this.button1.Text = "点击我";
this.button1.Click += new System.EventHandler(this.button1OnClick);
//
// button2
//
this.button2.Location = new System.Drawing.Point(162, 160);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(72, 24);
this.button2.TabIndex = 2;
this.button2.Text = "终结者";
this.button2.Click += new System.EventHandler(this.button2OnClick);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(292, 273);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.button2,
this.button1,
this.textBox1});
this.Name = "Form1";
this.Text = "我爱C#";
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1()); //启动程序
}
//响应单击按钮“点击我”的button1OnClick事件
private void button1OnClick(object sender, System.EventArgs e)
{
textBox1.Text="你好!电脑报";
//
}
//响应单击按钮“终结者”的button2OnClick事件
private void button2OnClick(object sender, System.EventArgs e)
{
Application.Exit(); //退出应用程序
}
}
}