TextBox 文本框控件

本教程将详细介绍C# Windows Forms应用程序中TextBox文本框控件的使用方法,包括基本属性设置、事件处理、数据验证、样式定制等内容,帮助您掌握文本框控件的各种应用场景。

1. 概述

TextBox控件是Windows Forms中最常用的控件之一,用于接收和显示用户输入的文本。TextBox控件支持单行和多行文本输入,可以设置密码显示模式,支持文本选择、复制、粘贴等操作,是构建用户界面的重要组成部分。

2. 创建TextBox控件

在Windows Forms应用程序中创建TextBox控件有两种主要方法:

2.1 通过设计器创建

  1. 打开Visual Studio,创建一个Windows Forms项目
  2. 在工具箱中找到TextBox控件
  3. 将TextBox控件拖放到窗体上
  4. 使用属性窗口设置TextBox的属性

2.2 通过代码创建

示例:通过代码创建TextBox控件

using System;
using System.Drawing;
using System.Windows.Forms;

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        CreateTextBox();
    }

    private void CreateTextBox()
    {
        // 创建TextBox控件
        TextBox textBox = new TextBox();
        
        // 设置TextBox属性
        textBox.Location = new Point(50, 50);
        textBox.Size = new Size(200, 30);
        textBox.Name = "txtName";
        textBox.PlaceholderText = "请输入姓名";
        
        // 添加文本改变事件处理程序
        textBox.TextChanged += new EventHandler(textBox_TextChanged);
        
        // 将TextBox添加到窗体
        this.Controls.Add(textBox);
    }

    private void textBox_TextChanged(object sender, EventArgs e)
    {
        TextBox textBox = (TextBox)sender;
        Console.WriteLine($"文本已改变:{textBox.Text}");
    }
}

3. TextBox控件的常用属性

TextBox控件有许多属性可以设置,以下是一些常用的属性:

属性 描述 示例值
Text 文本框中的文本内容 "Hello World"
Name 文本框的名称,用于在代码中引用 "txtName"
Location 文本框在窗体上的位置 new Point(100, 100)
Size 文本框的大小 new Size(200, 30)
Enabled 文本框是否可用 true/false
Visible 文本框是否可见 true/false
ReadOnly 文本框是否为只读 true/false
MaxLength 文本框中可输入的最大字符数 50
MultiLine 是否为多行文本框 true/false
ScrollBars 多行文本框的滚动条样式 ScrollBars.Vertical
PasswordChar 密码字符,用于隐藏输入的文本 '*'
UseSystemPasswordChar 是否使用系统密码字符 true/false
CharacterCasing 字符大小写转换 CharacterCasing.Upper
TextAlign 文本对齐方式 HorizontalAlignment.Center
BorderStyle 边框样式 BorderStyle.FixedSingle
BackColor 背景颜色 Color.White
ForeColor 文本颜色 Color.Black
Font 文本字体 new Font("微软雅黑", 10)
PlaceholderText 占位符文本(提示文本) "请输入..."
TabIndex Tab键顺序 1
TabStop 是否可以通过Tab键获得焦点 true/false

4. TextBox控件的常用事件

TextBox控件有多个事件,以下是最常用的事件:

事件 描述 示例
TextChanged 文本框中的文本发生改变时触发 private void textBox1_TextChanged(object sender, EventArgs e) { }
KeyDown 在文本框中按下键盘按键时触发 private void textBox1_KeyDown(object sender, KeyEventArgs e) { }
KeyPress 在文本框中按下并释放键盘按键时触发 private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { }
KeyUp 在文本框中释放键盘按键时触发 private void textBox1_KeyUp(object sender, KeyEventArgs e) { }
Enter 文本框获得焦点时触发 private void textBox1_Enter(object sender, EventArgs e) { }
Leave 文本框失去焦点时触发 private void textBox1_Leave(object sender, EventArgs e) { }
GotFocus 文本框获得焦点时触发 private void textBox1_GotFocus(object sender, EventArgs e) { }
LostFocus 文本框失去焦点时触发 private void textBox1_LostFocus(object sender, EventArgs e) { }
Click 单击文本框时触发 private void textBox1_Click(object sender, EventArgs e) { }
DoubleClick 双击文本框时触发 private void textBox1_DoubleClick(object sender, EventArgs e) { }
MouseEnter 鼠标进入文本框时触发 private void textBox1_MouseEnter(object sender, EventArgs e) { }
MouseLeave 鼠标离开文本框时触发 private void textBox1_MouseLeave(object sender, EventArgs e) { }

5. TextBox控件的常用方法

TextBox控件有一些常用的方法,以下是一些重要的方法:

方法 描述 示例
Clear() 清除文本框中的所有文本 textBox1.Clear();
Copy() 将选中的文本复制到剪贴板 textBox1.Copy();
Cut() 将选中的文本剪切到剪贴板 textBox1.Cut();
Paste() 将剪贴板中的文本粘贴到文本框 textBox1.Paste();
Undo() 撤销上一次操作 textBox1.Undo();
SelectAll() 选中文本框中的所有文本 textBox1.SelectAll();
Select(start, length) 选中指定范围的文本 textBox1.Select(0, 5);
Focus() 使文本框获得焦点 textBox1.Focus();
AppendText(text) 在文本框末尾追加文本 textBox1.AppendText("Hello");

6. TextBox控件的常见应用场景

6.1 单行文本输入

示例:创建单行文本输入框

// 创建单行文本框
TextBox txtName = new TextBox();
txtName.Location = new Point(50, 50);
txtName.Size = new Size(200, 30);
txtName.MaxLength = 20; // 限制最大输入长度
txtName.PlaceholderText = "请输入姓名(最多20个字符)";
txtName.Name = "txtName";
this.Controls.Add(txtName);

6.2 多行文本输入

示例:创建多行文本输入框

// 创建多行文本框
TextBox txtDescription = new TextBox();
txtDescription.Location = new Point(50, 100);
txtDescription.Size = new Size(300, 150);
txtDescription.Multiline = true; // 设置为多行模式
txtDescription.ScrollBars = ScrollBars.Vertical; // 显示垂直滚动条
txtDescription.PlaceholderText = "请输入描述信息...";
txtDescription.Name = "txtDescription";
this.Controls.Add(txtDescription);

6.3 密码输入框

示例:创建密码输入框

// 创建密码输入框
TextBox txtPassword = new TextBox();
txtPassword.Location = new Point(50, 150);
txtPassword.Size = new Size(200, 30);
txtPassword.PasswordChar = '*'; // 设置密码字符
txtPassword.MaxLength = 20; // 限制密码长度
txtPassword.PlaceholderText = "请输入密码";
txtPassword.Name = "txtPassword";
this.Controls.Add(txtPassword);

// 或者使用系统密码字符
txtPassword.UseSystemPasswordChar = true;

6.4 只读文本框

示例:创建只读文本框

// 创建只读文本框
TextBox txtReadOnly = new TextBox();
txtReadOnly.Location = new Point(50, 200);
txtReadOnly.Size = new Size(300, 30);
txtReadOnly.ReadOnly = true; // 设置为只读
txtReadOnly.Text = "这是只读文本框,用户无法修改";
txtReadOnly.BackColor = Color.LightGray; // 设置背景色提示只读状态
txtReadOnly.Name = "txtReadOnly";
this.Controls.Add(txtReadOnly);

6.5 数字输入框

示例:创建数字输入框

// 创建数字输入框
TextBox txtNumber = new TextBox();
txtNumber.Location = new Point(50, 250);
txtNumber.Size = new Size(200, 30);
txtNumber.PlaceholderText = "请输入数字";
txtNumber.Name = "txtNumber";
txtNumber.KeyPress += TxtNumber_KeyPress; // 添加KeyPress事件
this.Controls.Add(txtNumber);

// 只允许输入数字
private void TxtNumber_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsDigit(e.KeyChar) && e.KeyChar != (char)Keys.Back)
    {
        e.Handled = true; // 阻止输入非数字字符
    }
}

7. TextBox控件的数据验证

7.1 必填验证

示例:必填验证

private void btnSubmit_Click(object sender, EventArgs e)
{
    if (string.IsNullOrWhiteSpace(txtName.Text))
    {
        MessageBox.Show("姓名不能为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        txtName.Focus();
        return;
    }
    
    // 处理提交逻辑
    MessageBox.Show($"提交成功!姓名:{txtName.Text}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

7.2 格式验证

示例:邮箱格式验证

private void btnSubmit_Click(object sender, EventArgs e)
{
    string email = txtEmail.Text;
    
    if (string.IsNullOrWhiteSpace(email))
    {
        MessageBox.Show("邮箱不能为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        txtEmail.Focus();
        return;
    }
    
    // 验证邮箱格式
    if (!IsValidEmail(email))
    {
        MessageBox.Show("邮箱格式不正确!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        txtEmail.Focus();
        return;
    }
    
    // 处理提交逻辑
    MessageBox.Show($"提交成功!邮箱:{email}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

private bool IsValidEmail(string email)
{
    try
    {
        var addr = new System.Net.Mail.MailAddress(email);
        return addr.Address == email;
    }
    catch
    {
        return false;
    }
}

7.3 范围验证

示例:年龄范围验证

private void btnSubmit_Click(object sender, EventArgs e)
{
    if (!int.TryParse(txtAge.Text, out int age))
    {
        MessageBox.Show("请输入有效的年龄!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        txtAge.Focus();
        return;
    }
    
    if (age < 0 || age > 150)
    {
        MessageBox.Show("年龄必须在0到150之间!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        txtAge.Focus();
        return;
    }
    
    // 处理提交逻辑
    MessageBox.Show($"提交成功!年龄:{age}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

8. TextBox控件的样式定制

8.1 自定义颜色样式

示例:自定义颜色样式

// 设置自定义颜色
txtName.BackColor = Color.FromArgb(240, 240, 240);
txtName.ForeColor = Color.FromArgb(51, 51, 51);
txtName.BorderStyle = BorderStyle.FixedSingle;
txtName.Font = new Font("微软雅黑", 10);

// 设置获得焦点时的样式
txtName.Enter += (sender, e) =>
{
    txtName.BackColor = Color.White;
    txtName.BorderStyle = BorderStyle.FixedSingle;
};

txtName.Leave += (sender, e) =>
{
    txtName.BackColor = Color.FromArgb(240, 240, 240);
};

8.2 占位符效果

示例:实现占位符效果

// 在TextBox的Enter和Leave事件中实现占位符效果
private string placeholderText = "请输入姓名";

private void txtName_Enter(object sender, EventArgs e)
{
    if (txtName.Text == placeholderText)
    {
        txtName.Text = "";
        txtName.ForeColor = Color.Black;
    }
}

private void txtName_Leave(object sender, EventArgs e)
{
    if (string.IsNullOrWhiteSpace(txtName.Text))
    {
        txtName.Text = placeholderText;
        txtName.ForeColor = Color.Gray;
    }
}

// 在窗体加载时设置初始占位符
private void Form1_Load(object sender, EventArgs e)
{
    txtName.Text = placeholderText;
    txtName.ForeColor = Color.Gray;
}

9. TextBox控件的高级用法

9.1 自动完成功能

示例:实现自动完成功能

// 设置自动完成模式
txtName.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
txtName.AutoCompleteSource = AutoCompleteSource.CustomSource;

// 添加自动完成项
AutoCompleteStringCollection collection = new AutoCompleteStringCollection();
collection.AddRange(new string[] { "张三", "李四", "王五", "赵六" });
txtName.AutoCompleteCustomSource = collection;

9.2 文本选择操作

示例:文本选择操作

// 选中所有文本
txtName.SelectAll();

// 选中指定范围的文本
txtName.Select(0, 5); // 从第0个字符开始,选中5个字符

// 获取选中的文本
string selectedText = txtName.SelectedText;

// 获取选中文本的起始位置
int selectionStart = txtName.SelectionStart;

// 获取选中文本的长度
int selectionLength = txtName.SelectionLength;

// 设置选中文本
txtName.SelectionStart = 0;
txtName.SelectionLength = 5;

9.3 撤销和重做

示例:实现撤销和重做功能

// 撤销操作
txtName.Undo();

// 重做操作
txtName.Redo();

// 检查是否可以撤销
bool canUndo = txtName.CanUndo;

// 检查是否可以重做
bool canRedo = txtName.CanRedo;

// 清除撤销缓冲区
txtName.ClearUndo();

10. 完整示例程序

示例:用户注册表单

using System;
using System.Drawing;
using System.Windows.Forms;

namespace TextBoxExample
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            SetupForm();
        }
        
        private void SetupForm()
        {
            this.Text = "用户注册";
            this.Size = new Size(400, 350);
            this.StartPosition = FormStartPosition.CenterScreen;
            
            // 创建标签
            Label lblName = new Label();
            lblName.Text = "姓名:";
            lblName.Location = new Point(20, 20);
            lblName.Size = new Size(60, 20);
            this.Controls.Add(lblName);
            
            Label lblEmail = new Label();
            lblEmail.Text = "邮箱:";
            lblEmail.Location = new Point(20, 70);
            lblEmail.Size = new Size(60, 20);
            this.Controls.Add(lblEmail);
            
            Label lblPassword = new Label();
            lblPassword.Text = "密码:";
            lblPassword.Location = new Point(20, 120);
            lblPassword.Size = new Size(60, 20);
            this.Controls.Add(lblPassword);
            
            Label lblDescription = new Label();
            lblDescription.Text = "描述:";
            lblDescription.Location = new Point(20, 170);
            lblDescription.Size = new Size(60, 20);
            this.Controls.Add(lblDescription);
            
            // 创建文本框
            TextBox txtName = new TextBox();
            txtName.Name = "txtName";
            txtName.Location = new Point(90, 20);
            txtName.Size = new Size(250, 30);
            txtName.MaxLength = 20;
            txtName.PlaceholderText = "请输入姓名";
            txtName.TextChanged += ValidateInputs;
            this.Controls.Add(txtName);
            
            TextBox txtEmail = new TextBox();
            txtEmail.Name = "txtEmail";
            txtEmail.Location = new Point(90, 70);
            txtEmail.Size = new Size(250, 30);
            txtEmail.PlaceholderText = "请输入邮箱";
            txtEmail.TextChanged += ValidateInputs;
            this.Controls.Add(txtEmail);
            
            TextBox txtPassword = new TextBox();
            txtPassword.Name = "txtPassword";
            txtPassword.Location = new Point(90, 120);
            txtPassword.Size = new Size(250, 30);
            txtPassword.PasswordChar = '*';
            txtPassword.MaxLength = 20;
            txtPassword.PlaceholderText = "请输入密码";
            txtPassword.TextChanged += ValidateInputs;
            this.Controls.Add(txtPassword);
            
            TextBox txtDescription = new TextBox();
            txtDescription.Name = "txtDescription";
            txtDescription.Location = new Point(90, 170);
            txtDescription.Size = new Size(250, 80);
            txtDescription.Multiline = true;
            txtDescription.ScrollBars = ScrollBars.Vertical;
            txtDescription.PlaceholderText = "请输入描述信息";
            this.Controls.Add(txtDescription);
            
            // 创建按钮
            Button btnSubmit = new Button();
            btnSubmit.Name = "btnSubmit";
            btnSubmit.Text = "提交";
            btnSubmit.Location = new Point(90, 270);
            btnSubmit.Size = new Size(100, 40);
            btnSubmit.Enabled = false;
            btnSubmit.Click += BtnSubmit_Click;
            this.Controls.Add(btnSubmit);
            
            Button btnCancel = new Button();
            btnCancel.Name = "btnCancel";
            btnCancel.Text = "取消";
            btnCancel.Location = new Point(200, 270);
            btnCancel.Size = new Size(100, 40);
            btnCancel.Click += BtnCancel_Click;
            this.Controls.Add(btnCancel);
        }
        
        private void ValidateInputs(object sender, EventArgs e)
        {
            TextBox txtName = (TextBox)this.Controls.Find("txtName", true)[0];
            TextBox txtEmail = (TextBox)this.Controls.Find("txtEmail", true)[0];
            TextBox txtPassword = (TextBox)this.Controls.Find("txtPassword", true)[0];
            Button btnSubmit = (Button)this.Controls.Find("btnSubmit", true)[0];
            
            bool isValid = !string.IsNullOrWhiteSpace(txtName.Text) &&
                          !string.IsNullOrWhiteSpace(txtEmail.Text) &&
                          !string.IsNullOrWhiteSpace(txtPassword.Text);
            
            btnSubmit.Enabled = isValid;
        }
        
        private void BtnSubmit_Click(object sender, EventArgs e)
        {
            TextBox txtName = (TextBox)this.Controls.Find("txtName", true)[0];
            TextBox txtEmail = (TextBox)this.Controls.Find("txtEmail", true)[0];
            TextBox txtPassword = (TextBox)this.Controls.Find("txtPassword", true)[0];
            TextBox txtDescription = (TextBox)this.Controls.Find("txtDescription", true)[0];
            
            // 验证邮箱格式
            if (!IsValidEmail(txtEmail.Text))
            {
                MessageBox.Show("邮箱格式不正确!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtEmail.Focus();
                return;
            }
            
            // 验证密码长度
            if (txtPassword.Text.Length < 6)
            {
                MessageBox.Show("密码长度不能少于6位!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtPassword.Focus();
                return;
            }
            
            // 显示注册信息
            string message = $"注册成功!\n" +
                           $"姓名:{txtName.Text}\n" +
                           $"邮箱:{txtEmail.Text}\n" +
                           $"描述:{txtDescription.Text}";
            
            MessageBox.Show(message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        
        private void BtnCancel_Click(object sender, EventArgs e)
        {
            foreach (Control control in this.Controls)
            {
                if (control is TextBox)
                {
                    ((TextBox)control).Clear();
                }
            }
        }
        
        private bool IsValidEmail(string email)
        {
            try
            {
                var addr = new System.Net.Mail.MailAddress(email);
                return addr.Address == email;
            }
            catch
            {
                return false;
            }
        }
    }
}

11. 总结

通过本教程的学习,你应该掌握了C# Windows Forms中TextBox文本框控件的使用方法:

  • 如何创建TextBox控件(通过设计器和代码)
  • TextBox控件的常用属性设置
  • TextBox控件的常用事件处理
  • TextBox控件的常用方法
  • TextBox控件的常见应用场景(单行、多行、密码、只读、数字输入)
  • TextBox控件的数据验证(必填、格式、范围验证)
  • TextBox控件的样式定制
  • TextBox控件的高级用法(自动完成、文本选择、撤销重做)

TextBox控件是Windows Forms应用程序中最基础、最常用的控件之一,掌握好TextBox控件的使用方法,对于开发用户友好的桌面应用程序非常重要。在实际开发中,你可以根据具体需求,结合TextBox控件的各种属性和事件,创建出符合用户需求的输入界面。