Click here to Skip to main content
15,885,933 members
Articles / Programming Languages / C#
Article

DriveComboBox

Rate me:
Please Sign up or sign in to vote.
4.36/5 (12 votes)
20 Feb 2002 189.5K   2.2K   48   20
Ownerdrawn ComboBox that dispays all logical drives with appropriate icon, volume name and drive letter

Sample Image

Introduction

In this small example I used Directory.GetLogicalDrives() method to retieve the names of all logical drives.

Than I used GetDriveType(string driveLetter) method from kernel32.dll to get types of those drives (CDROM,FLOPPY,Local Disc etc.) so I knew what icon should be displayed next to the drive name.

The Drive names (Volume Labels) I got using GetVolumeInformation method from the same DLL as before.

C#
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;
using System.IO;
using System.Text;

struct DriveInfo
{
    private string letter;  //drive letter : "C:\","A:\"
    private int type;       //below
    private string name;    //Disc Label

    public int Type
    {
        get 
        {
            return type;
        }
    }

    public int Icon
    {
        get
        {
            if(name=="My Computer")return 0;
            if(type==5)return 3;//cd
            if(type==3)return 2;//fixed
            if(type==2)return 1;//removable
            if(type==4)return 4;//remote disk
            if(type==6)return 5;//ram disk
            return 6;//unknown
        }
    }

    public string Letter
    {
        get
        {
            if(letter!="")return " ("+letter+")";
            else return "";
        }
    }
    public string Name
    {
        get
        {
            if(name!="")return name;
            else{
                switch (this.Type)
                {
                    case 3:
                        if(letter==System.IO.Directory.GetDirectoryRoot(
                                              System.Environment.SystemDirectory))
                           return "System";
                        else 
                           return "Local Disc";
                    case 5:return "CD Rom";
                    case 6:return "RAM Disc";
                    case 4:return "Network Drive";
                    case 2:
                        if(letter=="A:\\")return "3.5 Floppy";
                        else return "Removable Disc";
                    default:return  "";
                }
            }
        }
    }

    //TYPE:
    //5-A CD-ROM drive. 
    //3-A hard drive. 
    //6-A RAM disk. 
    //4-A network drive or a drive located on a network server. 
    //2-A floppy drive or some other removable-disk drive. 
    public DriveInfo(string strLetter,int intType,string strName)
    {
        letter=strLetter;
        name=strName;
        type=intType;
    }
}

namespace ComboBox2
{
    /// <summary>
    /// Summary description for Form1.
    /// </summary>
    public class Form1 : System.Windows.Forms.Form
    {
        private System.Windows.Forms.ComboBox comboBox1;
        private System.ComponentModel.IContainer components;
        private System.Windows.Forms.ImageList imageList1;
        private System.Windows.Forms.Label label1;
        
        private ArrayList availableDrives = new ArrayList();


        [DllImport("kernel32.dll")]
        public static extern long GetDriveType(string driveLetter);
        [DllImport("kernel32.dll")]
        public static extern long GetVolumeInformation(string strPathName,
                                                       StringBuilder strVolumeNameBuffer,
                                                       long lngVolumeNameSize,
                                                       long lngVolumeSerialNumber,
                                                       long lngMaximumComponentLength,
                                                       long lngFileSystemFlags,
                                                       StringBuilder strFileSystemNameBuffer,
                                                       long lngFileSystemNameSize);

        public Form1()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
            findLogicalDrives();
            initDriveCombo();
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null) 
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.Resources.ResourceManager resources
                                 = new System.Resources.ResourceManager(typeof(Form1));
            this.comboBox1 = new System.Windows.Forms.ComboBox();
            this.imageList1 = new System.Windows.Forms.ImageList(this.components);
            this.label1 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            // 
            // comboBox1
            // 
            this.comboBox1.BackColor = System.Drawing.SystemColors.Window;
            this.comboBox1.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
            this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.comboBox1.DropDownWidth = 200;
            this.comboBox1.ForeColor = System.Drawing.SystemColors.WindowText;
            this.comboBox1.ItemHeight = 16;
            this.comboBox1.Location = new System.Drawing.Point(48, 40);
            this.comboBox1.Name = "comboBox1";
            this.comboBox1.Size = new System.Drawing.Size(200, 22);
            this.comboBox1.TabIndex = 0;
            this.comboBox1.DrawItem += 
                        new System.Windows.Forms.DrawItemEventHandler(this.OnComboDrawItem);
            // 
            // imageList1
            // 
            this.imageList1.ColorDepth = System.Windows.Forms.ColorDepth.Depth32Bit;
            this.imageList1.ImageSize = new System.Drawing.Size(16, 16);
            this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)
                                            (resources.GetObject("imageList1.ImageStream")));
            this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
            // 
            // label1
            // 
            this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif",
                                                        9.75F, 
                                                        System.Drawing.FontStyle.Regular, 
                                                        System.Drawing.GraphicsUnit.Point, 
                                                        ((System.Byte)(0)));
            this.label1.Location = new System.Drawing.Point(8, 40);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(40, 16);
            this.label1.TabIndex = 1;
            this.label1.Text = "Drive:";
            // 
            // Form1
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(292, 273);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                       this.label1,
                                                                       this.comboBox1});
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Name = "Form1";
            this.Text = "DriveComboBox";
            this.ResumeLayout(false);

        }
        #endregion

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main() 
        {
            Application.Run(new Form1());
        }

        private void OnComboDrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
        {
                Bitmap tempBitmap = new Bitmap(e.Bounds.Width,e.Bounds.Height,e.Graphics);
                Graphics tempGraphics = Graphics.FromImage(tempBitmap);
 
                //all items with offset, but MyComputer
                int offset=0;if(e.Index == 0)offset = 0;else offset = 20; 

                //item in comboBoxEdit no space in front
                if((e.State & DrawItemState.ComboBoxEdit)!=0)offset=0;

                if(e.Index == -1)return;// ???????????

                string tempLetter=((DriveInfo)availableDrives[e.Index]).Letter;
                string tempName=((DriveInfo)availableDrives[e.Index]).Name;
                string tempString = tempName+tempLetter;
                int tempIcon = ((DriveInfo)availableDrives[e.Index]).Icon;

                tempGraphics.FillRectangle(new SolidBrush(e.BackColor), 
                                   new Rectangle(0,0,tempBitmap.Width,tempBitmap.Height));
                tempGraphics.DrawString(tempString,e.Font ,new SolidBrush(e.ForeColor),
                                        new Point(28+offset,(tempBitmap.Height-e.Font.Height)/2));
                tempGraphics.DrawImage(imageList1.Images[tempIcon],
                                        new Rectangle(new Point(6+offset,0),new Size(16,16))); 
                
                e.Graphics.DrawImage(tempBitmap,e.Bounds.X,e.Bounds.Y);
        }



        public void findLogicalDrives()
        {
            string[] tempString = Directory.GetLogicalDrives();

            DriveInfo tempInfo = new DriveInfo("",0,"My Computer");
            availableDrives.Add(tempInfo);

            foreach(string tempDrive in tempString)
            {
                int tempType = getDriveType(tempDrive);
                string tempName = GetDriveName(tempDrive);
                tempInfo = new DriveInfo(tempDrive,tempType,tempName);
                availableDrives.Add(tempInfo);
            }

        }




        public int getDriveType(string drive)
        {
            if((GetDriveType(drive) & 5)==5)return 5;//cd
            if((GetDriveType(drive) & 3)==3)return 3;//fixed
            if((GetDriveType(drive) & 2)==2)return 2;//removable
            if((GetDriveType(drive) & 4)==4)return 4;//remote disk
            if((GetDriveType(drive) & 6)==6)return 6;//ram disk
            return 0;
        }


        public string GetDriveName(string drive)
        {
            //receives volume name of drive
            StringBuilder volname = new StringBuilder(256);
            //receives serial number of drive,not in case of network drive(win95/98)
            long sn= new long();
            long maxcomplen = new long();//receives maximum component length
            long sysflags = new long();//receives file system flags
            StringBuilder sysname = new StringBuilder(256);//receives the file system name
            long retval= new long();//return value

            retval = GetVolumeInformation(drive, volname, 256, sn, maxcomplen, 
                                          sysflags, sysname,256);
            
            if(retval!=0)return volname.ToString();
            else return "";
        }



        public void initDriveCombo()
        {
            foreach(DriveInfo tempDrvInfo in availableDrives)
            {
                comboBox1.Items.Add(tempDrvInfo.Letter);
            }
            comboBox1.SelectedIndex=0;
        }
    }
}

 

Comments, questions? odah@hotmail.com

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionHow to display all the items i.e., including my network places and all the folders that are residing on the desktop? Pin
tirumal12313-Jan-07 0:55
tirumal12313-Jan-07 0:55 
AnswerRe: How to display all the items i.e., including my network places and all the folders that are residing on the desktop? Pin
Michael B. Hansen8-May-07 20:15
Michael B. Hansen8-May-07 20:15 
GeneralVB.Net OnComboDrawItem Pin
HarSha9911-Nov-06 21:13
HarSha9911-Nov-06 21:13 
GeneralWrong PInvoke signature Pin
Mr. Say_how_it_is9-Feb-06 5:56
Mr. Say_how_it_is9-Feb-06 5:56 
GeneralBug: Horizontal Scrolling Pin
mikasa6-Jan-03 4:36
mikasa6-Jan-03 4:36 
Generalassociated icon for file Pin
SimonS6-Jun-02 1:15
SimonS6-Jun-02 1:15 
GeneralRe: associated icon for file Pin
cawoodm18-Jun-08 4:14
cawoodm18-Jun-08 4:14 
GeneralGetVolumeInformation: The Right Way (I hope ;) Pin
Andrea Balducci24-Mar-02 1:36
Andrea Balducci24-Mar-02 1:36 
Generalcompatibility Pin
4-Mar-02 4:31
suss4-Mar-02 4:31 
Is this a good way of programming.... I mean, concerning compatibility issues.....?

Louis
GeneralLooking for the real solution Pin
krausest25-Feb-02 22:42
krausest25-Feb-02 22:42 
GeneralRe: Looking for the real solution Pin
odah26-Feb-02 7:55
odah26-Feb-02 7:55 
GeneralRe: Looking for the real solution Pin
weariless10-Feb-05 17:25
weariless10-Feb-05 17:25 
GeneralRe: Looking for the real solution Pin
Gideon Engelberth6-Oct-05 16:57
Gideon Engelberth6-Oct-05 16:57 
AnswerRe: Looking for the real solution Pin
Michael B. Hansen8-May-07 20:13
Michael B. Hansen8-May-07 20:13 
GeneralError when compiling Pin
21-Feb-02 22:24
suss21-Feb-02 22:24 
GeneralRe: Error when compiling Pin
odah23-Feb-02 15:00
odah23-Feb-02 15:00 
GeneralRe: Error when compiling Pin
Anonymous11-Nov-02 10:30
Anonymous11-Nov-02 10:30 
GeneralRe: Error when compiling Pin
TigerNinja_23-Feb-02 15:54
TigerNinja_23-Feb-02 15:54 
GeneralA little question Pin
21-Feb-02 20:20
suss21-Feb-02 20:20 
GeneralRe: A little question Pin
odah23-Feb-02 16:23
odah23-Feb-02 16:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.