c#winform使用代码创建一个标签、一个文本输入框、一个按钮按下按钮后弹出文件夹选择窗口选择完成后将文件夹路径赋给文本输入框
以下是一个使用C# WinForm创建标签、文本输入框和按钮,并实现选择文件夹功能的示例代码:
using System;
using System.Windows.Forms;
namespace FolderSelectionExample
{
public partial class MainForm : Form
{
private Label folderLabel;
private TextBox folderTextBox;
private Button selectFolderButton;
public MainForm()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.folderLabel = new Label();
this.folderTextBox = new TextBox();
this.selectFolderButton = new Button();
this.SuspendLayout();
// 设置标签
this.folderLabel.AutoSize = true;
this.folderLabel.Location = new System.Drawing.Point(12, 9);
this.folderLabel.Name = "folderLabel";
this.folderLabel.Size = new System.Drawing.Size(76, 13);
this.folderLabel.Text = "选择文件夹:";
// 设置文本输入框
this.folderTextBox.Location = new System.Drawing.Point(94, 6);
this.folderTextBox.Name = "folderTextBox";
this.folderTextBox.Size = new System.Drawing.Size(200, 20);
this.folderTextBox.ReadOnly = true;
// 设置按钮
this.selectFolderButton.Location = new System.Drawing.Point(300, 4);
this.selectFolderButton.Name = "selectFolderButton";
this.selectFolderButton.Size = new System.Drawing.Size(75, 23);
this.selectFolderButton.Text = "选择";
this.selectFolderButton.Click += new System.EventHandler(this.SelectFolderButton_Click);
// 添加控件到窗口
this.Controls.Add(this.folderLabel);
this.Controls.Add(this.folderTextBox);
this.Controls.Add(this.selectFolderButton);
// 设置窗口
this.ClientSize = new System.Drawing.Size(387, 35);
this.Name = "MainForm";
this.Text = "文件夹选择示例";
this.ResumeLayout(false);
this.PerformLayout();
}
private void SelectFolderButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
if (folderDialog.ShowDialog() == DialogResult.OK)
{
folderTextBox.Text = folderDialog.SelectedPath;
}
}
}
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
}
在此示例中,我们创建了一个名为MainForm的窗口类,其中包含一个标签(folderLabel)、一个文本输入框(folderTextBox)和一个按钮(selectFolderButton)。在按钮的点击事件处理程序中,我们创建了一个FolderBrowserDialog来显示文件夹选择窗口,并在选择完成后将选中的文件夹路径赋给文本输入框(folderTextBox)的文本属性。
你可以将以上代码复制到一个C# WinForm项目中的MainForm.cs文件中,然后编译和运行该项目,即可看到窗口中的标签、文本输入框和按钮,并且在点击按钮后可以选择文件夹并将路径显示在文本输入框中。
原文地址: https://www.cveoy.top/t/topic/jeCE 著作权归作者所有。请勿转载和采集!