using System;
using System.Windows.Forms;
namespace WinFormExample
{
public class MainForm : Form
{
private Button button1;
private Label label1;
public MainForm()
{
// 初始化按钮
button1 = new Button
{
Text = "点击我",
Location = new System.Drawing.Point(50, 50),
Width = 100,
Height = 50
};
button1.Click += new EventHandler(Button1_Click);
// 初始化标签
label1 = new Label
{
Text = "你好,WinForms!",
Location = new System.Drawing.Point(50, 120),
Width = 200,
Height = 50
};
// 将控件添加到窗体
this.Controls.Add(button1);
this.Controls.Add(label1);
// 设置窗体属性
this.Text = "C# WinForms 示例";
this.Width = 300;
this.Height = 250;
}
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; 和 using System.Windows.Forms; 引入了必要的命名空间。public class MainForm : Form 定义了一个继承自 Form 的类 MainForm。构造函数:
public MainForm() 是窗体的构造函数,用于初始化窗体及其控件。button1 并设置了其文本、位置、宽度和高度。label1 并设置了其文本、位置、宽度和高度。按钮点击事件:
private void Button1_Click(object sender, EventArgs e) 是按钮点击事件的处理程序,当用户点击按钮时,会改变标签的文本内容。主程序入口:
[STAThread] static void Main() 是应用程序的入口点。Application.Run(new MainForm()) 启动应用程序并显示窗体。上一篇:c# byte数组转string
下一篇:c# =>
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站