«

C#中的Button控件

hujiato 发布于 阅读:91 编程


在 C# 中,Button控件是 Windows Forms 和 WPF 等 UI 框架中常用的交互元素,用于触发特定操作(如提交表单、执行命令等)。以下是关于Button控件的核心知识点:

1. 基本使用(Windows Forms)

在 Windows Forms 中,Button位于System.Windows.Forms命名空间,通常通过设计器拖放或代码创建。

创建与设置属性:

using System;
using System.Windows.Forms;

public class MyForm : Form
{
    public MyForm()
    {
        // 创建Button
        Button myButton = new Button();

        // 设置基本属性
        myButton.Text = "点击我";       // 显示文本
        myButton.Location = new System.Drawing.Point(50, 50);  // 位置(x,y)
        myButton.Size = new System.Drawing.Size(100, 30);      // 大小(宽,高)
        myButton.Name = "btnSubmit";    // 控件名称
        myButton.BackColor = System.Drawing.Color.LightBlue;   // 背景色

        // 添加到窗体
        this.Controls.Add(myButton);

        // 绑定点击事件
        myButton.Click += MyButton_Click;
    }

    // 点击事件处理方法
    private void MyButton_Click(object sender, EventArgs e)
    {
        MessageBox.Show("按钮被点击了!");
    }

    // 程序入口
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.Run(new MyForm());
    }
}

2. 常用属性

属性名 说明
Text 按钮上显示的文本
Name 控件的唯一标识名
Location 按钮在容器中的位置(Point类型)
Size 按钮的宽度和高度(Size类型)
Enabled 是否启用按钮(true/false
Visible 是否可见(true/false
BackColor 背景颜色
ForeColor 文本颜色
FlatStyle 扁平样式(如FlatPopup等)
Image 按钮上显示的图片

3. 常用事件

事件名 触发时机
Click 点击按钮时
MouseEnter 鼠标移入按钮时
MouseLeave 鼠标移出按钮时
KeyDown 按下键盘按键且焦点在按钮上时
EnabledChanged 按钮启用状态改变时

5. 高级用法

C#

文章目录