Geekpedia Tutorials Home

Building a C# Chat Client and Server

Building a C# Chat Client and ServerA step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.

in C# Programming Tutorials

Getting Hard Drive Information

Getting Hard Drive InformationA C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.

in C# Programming Tutorials

UPS Shipping Calculator

UPS Shipping CalculatorThis tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.

in PHP Programming Tutorials

Create Your Own Rich Text Editor

Create Your Own Rich Text EditorCreating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.

in JavaScript Programming Tutorials
Search
Tutorials
Programming Tutorials
IT Jobs
From CareerBuilder

Extracting Icons from Files

In this C# tutorial you will learn how to extract the graphic icon from a file by using a Shell32.dll API call to the unmanaged method SHGetFileInfo().

On Monday, September 3rd 2007 at 06:31 PM
By Andrew Pociu (View Profile)
*****   (Rated 5 with 7 votes)
Contextual Ads
More C# Resources
Advertisement
Download this Visual Studio 2005 project Download this project (Visual Studio 2005)

With this tutorial we're touching the unmanaged code of Windows again since we're going to use the SHGetFileInfo() API function. First let's add the needed reference to InteropServices:


using System.Runtime.InteropServices;


A bunch of constants we will use in the call to SHGetFileInfo() to specify the size of the icon we wish to retrieve:


// Constants that we need in the function call

private const int SHGFI_ICON = 0x100;

private const int SHGFI_SMALLICON = 0x1;

private const int SHGFI_LARGEICON = 0x0;


The SHFILEINFO structure is very important as it will be our handle to various file information, among which is the graphic icon.


// This structure will contain information about the file

public struct SHFILEINFO

{

    // Handle to the icon representing the file

    public IntPtr hIcon;

    // Index of the icon within the image list

    public int iIcon;

    // Various attributes of the file

    public uint dwAttributes;

    // Path to the file

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]

    public string szDisplayName;

    // File type

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]

    public string szTypeName;

};


The final preparation for the unmanaged code is to define the signature of SHGetFileInfo, which is located inside the popular Shell32.dll:


// The signature of SHGetFileInfo (located in Shell32.dll)

[DllImport("Shell32.dll")]

public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, int cbFileInfo, uint uFlags);


Now that we have everything prepared, it's time to make the call to the function and display the icon that we retrieved. The object that will be retrieved is an Icon type (System.Drawing.Icon) but we want to display it in a PictureBox so we'll convert the Icon to a Bitmap using the ToBitmap() method.

But first of all there are 3 controls you need to add to the form, a Button btnExtract that has "Extract Icon" for its Text property, picIconSmall which is a PictureBox and a picIconLarge which is also a PictureBox. That's because we will get two icons sizes. Now double click btnExtract in Visual Studio's Design view and you'll get to its Click event. Inside it is the rest of the code:


private void btnExtract_Click(object sender, EventArgs e)

{

    // Will store a handle to the small icon

    IntPtr hImgSmall;

    // Will store a handle to the large icon

    IntPtr hImgLarge;

 

    SHFILEINFO shinfo = new SHFILEINFO();

 

    // Open the file that we wish to extract the icon from

    if(openFile.ShowDialog() == DialogResult.OK)

    {

        // Store the file name

        string FileName = openFile.FileName;

        // Sore the icon in this myIcon object

        System.Drawing.Icon myIcon;

 

        // Get a handle to the small icon

        hImgSmall = SHGetFileInfo(FileName, 0, ref shinfo, Marshal.SizeOf(shinfo), SHGFI_ICON | SHGFI_SMALLICON);

        // Get the small icon from the handle

        myIcon = System.Drawing.Icon.FromHandle(shinfo.hIcon);

        // Display the small icon

        picIconSmall.Image = myIcon.ToBitmap();

 

        // Get a handle to the large icon

        hImgLarge = SHGetFileInfo(FileName, 0, ref shinfo, Marshal.SizeOf(shinfo), SHGFI_ICON | SHGFI_LARGEICON);

        // Get the large icon from the handle

        myIcon = System.Drawing.Icon.FromHandle(shinfo.hIcon);

        // Display the large icon

        picIconLarge.Image = myIcon.ToBitmap();

 

    }

}


It's pretty much self explanatory with all the comments, but if you have questions, you can always leave a comment. Here's the Icon Extractor application in action:

Icon Extract Application

Below is the full source code of the application. You can also download this in a Visual Studio 2005 solution using the link at the top of the tutorial.


using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Runtime.InteropServices;

 

namespace ExtractIcon

{

    public partial class Form1 : Form

    {

        // Constants that we need in the function call

        private const int SHGFI_ICON = 0x100;

        private const int SHGFI_SMALLICON = 0x1;

        private const int SHGFI_LARGEICON = 0x0;

 

        // This structure will contain information about the file

        public struct SHFILEINFO

        {

            // Handle to the icon representing the file

            public IntPtr hIcon;

            // Index of the icon within the image list

            public int iIcon;

            // Various attributes of the file

            public uint dwAttributes;

            // Path to the file

            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]

            public string szDisplayName;

            // File type

            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]

            public string szTypeName;

        };

 

        // The signature of SHGetFileInfo (located in Shell32.dll)

        [DllImport("Shell32.dll")]

        public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, int cbFileInfo, uint uFlags);

 

        public Form1()

        {

            InitializeComponent();

        }

 

        private void btnExtract_Click(object sender, EventArgs e)

        {

            // Will store a handle to the small icon

            IntPtr hImgSmall;

            // Will store a handle to the large icon

            IntPtr hImgLarge;

 

            SHFILEINFO shinfo = new SHFILEINFO();

 

            // Open the file that we wish to extract the icon from

            if(openFile.ShowDialog() == DialogResult.OK)

            {

                // Store the file name

                string FileName = openFile.FileName;

                // Sore the icon in this myIcon object

                System.Drawing.Icon myIcon;

 

                // Get a handle to the small icon

                hImgSmall = SHGetFileInfo(FileName, 0, ref shinfo, Marshal.SizeOf(shinfo), SHGFI_ICON | SHGFI_SMALLICON);

                // Get the small icon from the handle

                myIcon = System.Drawing.Icon.FromHandle(shinfo.hIcon);

                // Display the small icon

                picIconSmall.Image = myIcon.ToBitmap();

 

                // Get a handle to the large icon

                hImgLarge = SHGetFileInfo(FileName, 0, ref shinfo, Marshal.SizeOf(shinfo), SHGFI_ICON | SHGFI_LARGEICON);

                // Get the large icon from the handle

                myIcon = System.Drawing.Icon.FromHandle(shinfo.hIcon);

                // Display the large icon

                picIconLarge.Image = myIcon.ToBitmap();

 

            }

        }

    }

}

Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by VGstudios Owner on Tuesday, September 4th 2007 at 02:47 PM

Nice tutorial man!!!! Now you get a free mouse pad =P

by Andrei on Tuesday, September 4th 2007 at 03:05 PM

I'll make sure I get one :-)
Did yours arrive yet?

by }{ombr3 on Wednesday, September 12th 2007 at 06:36 AM

Nice tool!!

But why do you nowhere need a mouse pad anyway?? ^^

Finally I only want to say that you forgot to mention the FileOpenDialog called "openFile" :)

Greetz

by }{ombr3 on Wednesday, September 12th 2007 at 06:37 AM

Sorry... i mean "nowadays" instead of "nowhere"... my english is really bad *URK*

by haris on Sunday, June 22nd 2008 at 11:49 AM

is there any way to extract all the icons in a PE file....if u know it i will be really thankful to u if u help me out....thanx

by gg on Wednesday, April 1st 2009 at 07:21 AM

gsggf

by Zach on Thursday, April 7th 2011 at 07:09 PM

That is an awesome tutorial! And is already implemented into my code :)

I would like to add a feature and maybe you can help. How would I go about changing the icon with another icon that is on the hard drive (I will have an exact directory to it)??

by Akram on Thursday, June 2nd 2011 at 04:22 AM

Awesome tutorial

by happy birthday wishes on Saturday, August 13th 2011 at 02:46 PM

Thanks for this useable airman - I increase your acquisition ! Foreclose on work.

by good morning sms on Wednesday, August 17th 2011 at 02:23 AM

is there any way to extract all the icons in a PE file....if u know it i will be really thankful to u if u help me out....thanx

by magazine subscriptions- on Monday, December 12th 2011 at 04:58 AM

Looks like you don't have permission over the Insert command. Check the user's credentials.and plix help me with the ASP code, for login. i want the registered users to login.When logging in the details should be retrieved from the database.

by GenF20 Plus on Monday, December 19th 2011 at 05:25 PM

This is a great trick and I didn’t know you can use C# to obtain the info of your computer

by Human Growth Hormone on Monday, December 19th 2011 at 05:29 PM

This is a great trick and I didn’t know you can use C# to obtain the info of your computer

by Phen375 on Monday, December 19th 2011 at 05:34 PM

Does this trick work for Mac too?

by GenFX on Monday, December 19th 2011 at 05:36 PM

Does this trick work for Mac too?

by Teeth Whitening Reviews on Monday, December 19th 2011 at 05:42 PM

I needed to create you this tiny word so as to give thanks once again for your pleasant techniques you have provided on this site. This has been shockingly open-handed with people like you to supply openly what exactly a number of people would've offered for an e book to help make some profit for themselves, precisely now that you could possibly have done it in case you desired.

by Nuratrim on Monday, December 19th 2011 at 05:43 PM

I needed to create you this tiny word so as to give thanks once again for your pleasant techniques you have provided on this site. This has been shockingly open-handed with people like you to supply openly what exactly a number of people would've offered for an e book to help make some profit for themselves, precisely now that you could possibly have done it in case you desired.

by Ultimate Maqui Berry on Monday, December 19th 2011 at 05:47 PM

Those concepts additionally worked as a good way to recognize that other people have the same desire really like my own to see significantly more in regard to this issue. Certainly there are numerous more pleasurable opportunities up front for people who looked over your blog.

by Best Diet Pills on Monday, December 19th 2011 at 05:48 PM

Those concepts additionally worked as a good way to recognize that other people have the same desire really like my own to see significantly more in regard to this issue. Certainly there are numerous more pleasurable opportunities up front for people who looked over your blog.

by Dental White on Monday, December 19th 2011 at 05:50 PM

I have to express my thanks to the writer just for rescuing me from such a difficulty. Because of browsing through the online world and seeing views which were not helpful, I believed my life was done. Existing without the presence of solutions to the problems you've fixed as a result of your main write-up is a crucial case, and the kind which could have in a wrong way affected my entire career if I hadn't discovered your website.

by Pure Acai Berry Max on Monday, December 19th 2011 at 05:53 PM

I have to express my thanks to the writer just for rescuing me from such a difficulty. Because of browsing through the online world and seeing views which were not helpful, I believed my life was done. Existing without the presence of solutions to the problems you've fixed as a result of your main write-up is a crucial case, and the kind which could have in a wrong way affected my entire career if I hadn't discovered your website.

by john on Saturday, January 14th 2012 at 01:12 AM

Once you have recreated the problem and captured these steps, you can save them to a file and send it to your support person, who can then open it up and view

by beats by dre stu on Thursday, March 1st 2012 at 09:29 PM

You will be getting plenty of visitors to your website from me!

by Gizmo on Saturday, December 28th 2013 at 12:06 AM

The only one that works on the entire internet.


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs C# Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Ads

From the creators of Geekpedia, a revolutionary new coupon website!

BargainEZ has coupons codes, printable coupons, bargains and it is the leading source of Passbook coupons for iPhone and iPod touch devices.

Coupons
Discover Geekpedia
Other Resources