Click here to Skip to main content
Licence 
First Posted 20 Feb 2002
Views 163,013
Bookmarked 47 times

DriveComboBox

By | 20 Feb 2002 | Article
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.

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

About the Author

odah



United States United States

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionHow to display all the items i.e., including my network places and all the folders that are residing on the desktop? Pinmembertirumal12310:55 3 Jan '07  
AnswerRe: How to display all the items i.e., including my network places and all the folders that are residing on the desktop? PinmemberMichael B. Hansen20:15 8 May '07  
GeneralVB.Net OnComboDrawItem PinmemberHarSha9921:13 11 Nov '06  
GeneralWrong PInvoke signature PinmemberOliver_D5:56 9 Feb '06  
GeneralBug: Horizontal Scrolling Pinmembermikasa4:36 6 Jan '03  
Generalassociated icon for file PinmemberSimonS1:15 6 Jun '02  
GeneralRe: associated icon for file Pinmembercawoodm4:14 18 Jun '08  
GeneralGetVolumeInformation: The Right Way (I hope ;) PinmemberAndrea Balducci1:36 24 Mar '02  
Generalcompatibility PinmemberAnonymous4:31 4 Mar '02  
GeneralLooking for the real solution Pinmemberkrausest22:42 25 Feb '02  
GeneralRe: Looking for the real solution Pinmemberodah7:55 26 Feb '02  
GeneralRe: Looking for the real solution Pinmemberweariless17:25 10 Feb '05  
GeneralRe: Looking for the real solution PinmemberGideon Engelberth16:57 6 Oct '05  
AnswerRe: Looking for the real solution PinmemberMichael B. Hansen20:13 8 May '07  
GeneralError when compiling PinmemberFeda22:24 21 Feb '02  
GeneralRe: Error when compiling Pinmemberodah15:00 23 Feb '02  
GeneralRe: Error when compiling PinsussAnonymous10:30 11 Nov '02  
GeneralRe: Error when compiling PinmemberSoliant15:54 23 Feb '02  
GeneralA little question PinmemberXavier Lelievre20:20 21 Feb '02  
GeneralRe: A little question Pinmemberodah16:23 23 Feb '02  
If you talking about return values:
The function GetDriveType
in Winbase.h is declared like this:
 
UINT GetDriveType(
LPCTSTR lpRootPathName // root directory
);
 
so
as you can see the return value is unsigned integer.
Smile | :)
The declaration of GetVolumeInformation in the same header
file looks like this:
 
BOOL GetVolumeInformationW(
IN LPCWSTR lpRootPathName,
OUT LPWSTR lpVolumeNameBuffer,
IN DWORD nVolumeNameSize,
OUT LPDWORD lpVolumeSerialNumber,
OUT LPDWORD lpMaximumComponentLength,
OUT LPDWORD lpFileSystemFlags,
OUT LPWSTR lpFileSystemNameBuffer,
IN DWORD nFileSystemNameSize
);
 
function returns zero or nonzero value, zero is equivalent to false , and nonzero is equivalent
to true,in C++ this conversion is OK , in C#, there is no conversion between the bool type and other types ,so I could not use BOOL , but I use long instead.
 
If you use int as return value in this function you would get 1(one) if all the requested information is retrieved .If not all the requested information is retrieved you would get 0(zero).

 
odah

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

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120529.1 | Last Updated 21 Feb 2002
Article Copyright 2002 by odah
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid