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

C# WinForm 文件夹选择器:使用代码创建标签、文本框和按钮

原文地址: https://www.cveoy.top/t/topic/fhdP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录