自动显示打开磁盘分区的按钮

时间:2017-04-10 17:03:49

标签: c# .net winforms

我正在做文件管理器。启动程序时,必须显示选择现有磁盘分区的按钮。目前,一切都按照下面的代码进行。简单地说,有四个按钮带有" C"," D"," E"," F"但突然之间用户只有" C",那么应该只有一个" C"按钮。

private void button10_Click(object sender, EventArgs e)
{
    webBrowser1.Navigate(@"C:\");
}

1 个答案:

答案 0 :(得分:1)

您可以通过以下方式执行此操作:

using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

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

        private void Form1_Load(object sender, EventArgs e)
        {
            // We need to get all logic drives of the system on Forms load
            var localDrives = DriveInfo.GetDrives();
            int i = 0;
            foreach(DriveInfo localDrive in localDrives)
            {
                // Create for each Drive the specific button
                Button bt = new Button();
                // Add specific text to button
                bt.Text = localDrive.Name;
                // Set button's width
                bt.Width = 40;
                // Set location
                bt.Location =  new Point(10+40*i,10);
                i++;
                // Add event handler for click to open File Explorer for that drive
                bt.Click += new EventHandler((obj, args) =>
                {
                    // This will open File explorer to the given path
                    Process.Start(localDrive.RootDirectory.FullName);
                });
                // And finally add our button to the Form
                this.Controls.Add(bt);
            }
        }
    }
}

有关System.IO.DriveInfo的更多信息,您可以找到DriveInfo

有关System.Diagnostics.Process.Start的更多信息,您可以找到Process.Start