Click here to Skip to main content
Licence 
First Posted 20 Feb 2002
Views 161,614
Downloads 1,673
Bookmarked 46 times

DriveComboBox

By odah | 20 Feb 2002
Ownerdrawn ComboBox that dispays all logical drives with appropriate icon, volume name and drive letter

1
1 vote, 8.3%
2
2 votes, 16.7%
3
3 votes, 25.0%
4
6 votes, 50.0%
5
4.17/5 - 15 votes
μ 3.74, σa 1.80 [?]

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? Pinmembertirumal12311: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. Hansen21:15 8 May '07  
GeneralVB.Net OnComboDrawItem PinmemberHarSha9922:13 11 Nov '06  
GeneralWrong PInvoke signature PinmemberOliver_D6:56 9 Feb '06  
GeneralBug: Horizontal Scrolling Pinmembermikasa5:36 6 Jan '03  
Generalassociated icon for file PinmemberSimonS2:15 6 Jun '02  
GeneralRe: associated icon for file Pinmembercawoodm5:14 18 Jun '08  
GeneralGetVolumeInformation: The Right Way (I hope ;) PinmemberAndrea Balducci2:36 24 Mar '02  
Generalcompatibility PinmemberAnonymous5:31 4 Mar '02  
GeneralLooking for the real solution Pinmemberkrausest23:42 25 Feb '02  
GeneralRe: Looking for the real solution Pinmemberodah8:55 26 Feb '02  
GeneralRe: Looking for the real solution Pinmemberweariless18:25 10 Feb '05  
GeneralRe: Looking for the real solution PinmemberGideon Engelberth17:57 6 Oct '05  
AnswerRe: Looking for the real solution PinmemberMichael B. Hansen21:13 8 May '07  
GeneralError when compiling PinmemberFeda23:24 21 Feb '02  
GeneralRe: Error when compiling Pinmemberodah16:00 23 Feb '02  
GeneralRe: Error when compiling PinsussAnonymous11:30 11 Nov '02  
GeneralRe: Error when compiling PinmemberSoliant16:54 23 Feb '02  
GeneralA little question PinmemberXavier Lelievre21:20 21 Feb '02  
GeneralRe: A little question Pinmemberodah17:23 23 Feb '02  

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
Web02 | 2.5.120210.1 | Last Updated 21 Feb 2002
Article Copyright 2002 by odah
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid