驱动器框






2.56/5 (6投票s)
2001年7月5日
2分钟阅读

98684

985
本文档解释了如何在组合框中显示驱动器列表。
引言
驱动框控件允许用户在运行时选择有效的磁盘驱动器。该控件可用于显示用户系统上所有有效驱动器的列表。您可以创建对话框,允许用户从任何可用驱动器上的文件列表中打开文件。此控件与我们非常熟悉的 DriveListBox 控件非常相似。
入门
为了使驱动框显示有效的磁盘驱动器,我们需要找出用户系统中的可用驱动器。一旦获得可用的驱动器信息,就可以将其显示在 ComboBox 中。
Directory 类
为了获得可用的驱动器,.Net 框架为我们提供了 Directory
类。该类定义在 System.IO
命名空间中。该类公开了获取本地驱动器、创建、移动和枚举目录和子目录的例程。我们感兴趣的方法是 Directory.GetLogicalDrives
方法。该方法的签名是
public static string[] GetLogicalDrives();
此方法以“C:\”的形式检索此计算机上的逻辑驱动器的名称。
namespace MyControls {
using System;
using System.IO;
using System.WinForms;
public sealed class DriveBox : ComboBox{
DriveBox(){
lstCollect = new ObjectCollection(this);
Style = ComboBoxStyle.DropDownList;
foreach (String str in Directory.GetLogicalDrives()){
str = str.Replace('\\',' ');
lstCollect.Add(str);
}
SelectedIndex = 0;
}
public String Drive{
get{
return Text;
}
}
}
}
上面的代码定义了 DriveBox 类。DriveBox 继承自 ComboBox,因此具有 ComboBox 的所有属性。DriveBox 设置为下拉列表样式。添加了一个新的属性 Drive,它返回当前选定的驱动器。
使用以下编译器选项编译程序。
csc filename.cs /out:MyControls.dll /target:library
测试应用程序
现在让我们尝试在小型测试应用程序中使用驱动框。此测试应用程序将显示用户系统中的所有可用驱动器。当用户在驱动框中选择驱动器时,应用程序会显示一个消息框,提示当前选定的驱动器。
using System;
using System.WinForms;
using System.Drawing;
using MyControls;
public class DriveBoxTest: Form{
private Button btnOK = new Button();
private DriveBox dbxLocal = new DriveBox();
public static int Main(string[] args){
Application.Run(new DriveBoxTest());
return 0;
}
public DriveBoxTest(){
this.Text = "DriveBox Test Program";
dbxLocal.Location = new Point(1,10);
dbxLocal.Size = new Size(80,20);
btnOK.Location = new Point(90,100);
btnOK.Size = new Size(80,20);
btnOK.Text = "OK";
this.Controls.Add(btnOK);
this.Controls.Add(dbxLocal);
btnOK.Click += new System.EventHandler(btnOK_Click);
dbxLocal.SelectedIndexChanged +=
new System.EventHandler(dbxLocal_SelectedIndexChanged);
}
private void btnOK_Click(object sender, EventArgs evArgs){
Application.Exit();
}
private void dbxLocal_SelectedIndexChanged(object sender,
EventArgs evArgs){
MessageBox.Show(dbxLocal.Drive,"DriveBox");
}
}
使用以下编译器选项编译程序。
csc filename.cs /R:System.dll /R:System.WinForms.dll /R:System.Drawing.dll /R:MyControls.dll
应用程序的输出将如示例图像所示。