C# 窗体与控件详解

1. Windows Forms 窗体基础

窗体(Form)​ 是 Windows 应用程序的基本容器,用于承载控件并处理用户交互。

​创建窗体项目:

在 Visual Studio 中选择“Windows Forms App (.NET Framework)”模板。默认生成 Form1.cs(设计界面)和 Form1.Designer.cs(自动生成代码)。

​常用属性:

Text:窗体标题。Size:窗体尺寸。StartPosition:窗体首次显示的位置(如 CenterScreen)。FormBorderStyle:边框样式(如 FixedDialog 禁用调整大小)。

​窗体事件:

csharp

private void Form1_Load(object sender, EventArgs e) { } // 窗体加载时触发

private void Form1_FormClosing(object sender, FormClosingEventArgs e) { } // 关闭前触发

​显示窗体:

主窗体在 Program.cs 中通过 Application.Run(new Form1()); 启动。模态对话框:form.ShowDialog()(阻塞其他窗口)。非模态窗口:form.Show()。

2. 常用控件详解

2.1 Label 控件

​属性:

Text:显示的文本。Font:字体样式。ForeColor:文字颜色。

2.2 TextBox 控件

​属性:

Multiline:允许多行输入。PasswordChar:设置为 * 可隐藏输入(如密码框)。

​事件:

csharp

private void textBox1_TextChanged(object sender, EventArgs e)

{

label1.Text = $"输入长度:{textBox1.Text.Length}";

}

2.3 Button 控件

​事件:

csharp

private void button1_Click(object sender, EventArgs e)

{

MessageBox.Show("按钮被点击!");

}

2.4 ComboBox 和 ListBox

​添加项:

csharp

comboBox1.Items.Add("选项1");

listBox1.Items.AddRange(new[] { "Item1", "Item2" });

​获取选中项:

csharp

string selected = comboBox1.SelectedItem.ToString();

2.5 DataGridView

​绑定数据:

csharp

dataGridView1.DataSource = new BindingList(personsList);

3. 布局管理

​Anchor 和 Dock:

Anchor:控件随窗体调整位置(如靠右、底部)。Dock:控件填充到父容器的某侧(如 DockStyle.Top)。

​布局容器:

​Panel/GroupBox:分组控件。​FlowLayoutPanel:自动横向或纵向排列控件。​TableLayoutPanel:网格布局,支持行列比例。

4. 事件处理

​事件参数:

KeyPressEventArgs:获取按下的键。

csharp

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)

{

if (!char.IsDigit(e.KeyChar)) e.Handled = true; // 只允许数字输入

}

​多事件共享处理:

csharp

private void HandleButtonClick(object sender, EventArgs e)

{

Button btn = (Button)sender;

btn.Text = "已点击";

}

// 将多个按钮的 Click 事件指向同一方法

5. 数据绑定与验证

​简单绑定:

csharp

textBox1.DataBindings.Add("Text", person, "Name");

​ErrorProvider 验证:

csharp

private void textBox1_Validating(object sender, CancelEventArgs e)

{

if (string.IsNullOrEmpty(textBox1.Text))

errorProvider1.SetError(textBox1, "不能为空!");

else

errorProvider1.Clear();

}

6. 自定义控件

​创建用户控件:

右键项目 → 添加 → 用户控件(.cs)。拖放控件并添加逻辑。

csharp

public partial class MyCustomControl : UserControl

{

public MyCustomControl() { InitializeComponent(); }

}

​扩展现有控件:

csharp

public class NumericTextBox : TextBox

{

protected override void OnKeyPress(KeyPressEventArgs e)

{

if (!char.IsDigit(e.KeyChar)) e.Handled = true;

base.OnKeyPress(e);

}

}

7. 高级主题

​多线程更新 UI:

csharp

private void UpdateStatus(string message)

{

if (InvokeRequired)

Invoke(new Action(() => label1.Text = message));

else

label1.Text = message;

}

​不规则窗体:

csharp

this.FormBorderStyle = FormBorderStyle.None;

this.Region = new Region(new Rectangle(0, 0, 200, 200)); // 自定义形状

8. 实战示例:登录窗体

csharp

public partial class LoginForm : Form

{

public LoginForm() { InitializeComponent(); }

private void btnLogin_Click(object sender, EventArgs e)

{

if (txtUser.Text == "admin" && txtPass.Text == "123")

DialogResult = DialogResult.OK;

else

MessageBox.Show("登录失败!");

}

}

总结

通过系统学习窗体属性、控件使用、布局管理、事件处理及数据绑定,开发者能够构建功能丰富、用户友好的 Windows 应用程序。结合自定义控件和高级技术,可进一步提升界面体验和功能性。建议通过实际项目练习,加深对各个知识点的掌握。