using System;
using System.Windows.Forms;
namespace CSharpUIExample
{
public class MainForm : Form
{
private Button button1;
private Label label1;
public MainForm()
{
// 初始化按钮
button1 = new Button
{
Text = "点击我",
Location = new System.Drawing.Point(50, 50),
Size = new System.Drawing.Size(100, 50)
};
button1.Click += new EventHandler(Button1_Click);
// 初始化标签
label1 = new Label
{
Text = "欢迎使用C#界面示例",
Location = new System.Drawing.Point(50, 120),
Size = new System.Drawing.Size(200, 30)
};
// 将控件添加到窗体
this.Controls.Add(button1);
this.Controls.Add(label1);
// 设置窗体属性
this.Text = "C# 界面示例";
this.Size = new System.Drawing.Size(300, 300);
}
// 按钮点击事件处理程序
private void Button1_Click(object sender, EventArgs e)
{
label1.Text = "你点击了按钮!";
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
}
命名空间和类:
using System.Windows.Forms; 导入 Windows Forms 命名空间,用于创建图形用户界面。MainForm 类继承自 Form 类,表示应用程序的主窗口。控件初始化:
button1 是一个按钮控件,设置了其文本、位置和大小,并绑定了点击事件。label1 是一个标签控件,用于显示文本信息。事件处理:
Button1_Click 方法是按钮点击事件的处理程序,当按钮被点击时,会改变 label1 的文本内容。窗体设置:
this.Controls.Add() 方法将控件添加到窗体中。this.Text 和 this.Size 分别设置窗体的标题和大小。程序入口:
Main 方法是应用程序的入口点,调用 Application.Run(new MainForm()) 启动窗体应用程序。上一篇:c#格式化字符串
下一篇:c# 事件与委托使用场景
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站