C#创建一个自定义控件类

如果你希望在 TextBox 内部嵌入一个按钮,并且这个按钮用于打开文件选择对话框,可以创建一个自定义控件来实现这一功能。下面是一个示例,展示如何在 Windows 窗体应用程序中创建一个自定义控件,其中 Button 嵌入到 TextBox 内部。

首先,创建一个自定义控件类:

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

public class TextBoxWithButton : UserControl
{
    private TextBox textBox;
    private Button button;

    public TextBoxWithButton()
    {
        // 初始化 TextBox 控件
        textBox = new TextBox();
        textBox.Dock = DockStyle.Fill;
        textBox.Margin = new Padding(0);

        // 初始化 Button 控件
        button = new Button();
        button.Text = "...";
        button.Dock = DockStyle.Right;
        button.Width = 30;
        button.Margin = new Padding(0);

        // 按钮点击事件
        button.Click += new EventHandler(Button_Click);

        // 将控件添加到 UserControl 上
        this.Controls.Add(textBox);
        this.Controls.Add(button);

        // 设置 UserControl 的边距和大小
        this.Padding = new Padding(0);
        this.Size = new Size(230, textBox.Height);
    }

    private void Button_Click(object sender, EventArgs e)
    {
        // 这里可以实现按钮点击后的逻辑,例如打开文件选择器
        OpenFileDialog openFileDialog = new OpenFileDialog();
        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
            textBox.Text = openFileDialog.FileName;
        }
    }

    // 公开 TextBox 的 Text 属性
    public override string Text
    {
        get { return textBox.Text; }
        set { textBox.Text = value; }
    }
}
然后,在你的主窗体中使用这个自定义控件:

using System;
using System.Windows.Forms;

public class MainForm : Form
{
    private TextBoxWithButton textBoxWithButton;

    public MainForm()
    {
        // 初始化 TextBoxWithButton 控件
        textBoxWithButton = new TextBoxWithButton();
        textBoxWithButton.Location = new System.Drawing.Point(20, 20);

        // 将 TextBoxWithButton 控件添加到窗体上
        this.Controls.Add(textBoxWithButton);

        // 设置窗体属性
        this.Text = "嵌入按钮的 TextBox 示例";
        this.StartPosition = FormStartPosition.CenterScreen;
        this.Size = new System.Drawing.Size(300, 100);
    }

    [STAThread]
    public static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MainForm());
    }
}

在这个示例中:

创建了一个名为 TextBoxWithButton 的自定义控件,继承自 UserControl。
在 TextBoxWithButton 控件中,创建了一个 TextBox 和一个 Button,并将它们添加到控件中。
将 Button 的 Dock 属性设置为 DockStyle.Right,将 TextBox 的 Dock 属性设置为 DockStyle.Fill,使按钮嵌入到文本框的右侧。
在按钮的点击事件中,显示一个文件选择对话框,并将选中的文件路径显示在文本框中。
在主窗体中,创建并添加 TextBoxWithButton 控件。
运行这个示例代码后,你会看到一个带有“…”按钮的文本框,按钮嵌入在文本框内部,点击按钮会打开文件选择对话框,选择的文件路径会显示在文本框中。

  • 8
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值