How to Use Shell32 Within a C# Application

How to use Shell32 within a C# application?

Just add a reference to Shell32.dll from the Windows\System32 folder and use it:

Shell32.Shell shell = new Shell32.Shell();
shell.MinimizeAll();

Referencing Shell32.dll?

Shell32 is a COM server that you can use in your C# program. You however have to generate an interop assembly first to convert the type library inside shell32.dll (same idea as .NET metadata) to declarations that the CLR can understand. Either by running Tlbimp.exe or, much simpler, by adding a reference to the DLL in the IDE.

As long as you do this from the command line and don't use msbuild to get a .csproj project file compiled then you have to do the same thing that msbuild does, run tlbimp. For shell32.dll this only has to be done once and you can check-in the interop library in source control so you don't have to do it again. Use /r on the interop library.

Using the IDE or MSBuild.exe are of course the wise choices. Also helps you fall in the pit of success, you really want to use the Embed Interop Types feature so you don't need the interop assembly at runtime and don't have to deploy it. Looking at the build commands generated by MSBuild is useful.

C# - new Shell32() throw an exception?

Thank You, I've found the way with your comments.
I just need to use this as dynamic.

static readonly Guid CLSID_Shell = Guid.Parse("13709620-C279-11CE-A49E-444553540000");
dynamic shell = Activator.CreateInstance(Type.GetTypeFromCLSID(CLSID_Shell));

Also, If I add the STAThreadAttribute to my Main method it works without problems (credits goes to @Matthew Watson)

How can I use the images within shell32.dll in my C# project?

You can extract icons from a DLL with this code:

public class IconExtractor
{

public static Icon Extract(string file, int number, bool largeIcon)
{
IntPtr large;
IntPtr small;
ExtractIconEx(file, number, out large, out small, 1);
try
{
return Icon.FromHandle(largeIcon ? large : small);
}
catch
{
return null;
}

}
[DllImport("Shell32.dll", EntryPoint = "ExtractIconExW", CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
private static extern int ExtractIconEx(string sFile, int iIndex, out IntPtr piLargeVersion, out IntPtr piSmallVersion, int amountIcons);

}

...

form.Icon = IconExtractor.Extract("shell32.dll", 42, true);

Of course you need to know the index of the image in the DLL...

Reference shell32.dll in a programmatically compiled program?

Shell32.dll (Windows file systems don't care about case, so "s" or "S" shouldn't matter) is not a .NET assembly and thus can't be treated as such.

If you want to call functions exported from non-.NET libraries, you should use the DllImportAttribute.



Related Topics



Leave a reply



Submit