xproot
xproot

Reputation: 49

How do I import a Shell32.dll function in C#?

I'm sorry for my naiveness, it's my first time dealing with DLLs. I've been trying to run ShellAboutA on a C# Application and had absolutely no idea how to. I googled and found a couple of questions and managed to come up with this code

[DllImport("shell32.dll")]
        public static extern Int32 ShellAboutA(
            IntPtr? hWnd,
            IntPtr? szApp,
            IntPtr? szOtherStuff,
            UInt64? hIcon);

ShellAboutA(null, null, null, null);

but once I ran it, it errored with

System.Runtime.InteropServices.MarshalDirectiveException: 'Cannot marshal 'parameter #1': Generic types cannot be marshaled.'

(not only do I have no idea how to work with DLLs but I also have no idea what this means)

I'm guessing it's probably because they are all null. I checked the documentation again and everything but szApp is NULLable, so I tried this next function

            string _str = "test string";
            Int64 _int = Convert.ToInt64(_str, 16);
            IntPtr test = new IntPtr(_int);
            ShellAboutA(null, test, null, null);

and _int fails in System.FormatException: 'Could not find any recognizable digits.' no matter how much googling I did after this, I found no solution.

Upvotes: 1

Views: 779

Answers (1)

Charlieface
Charlieface

Reputation: 71586

There are a bunch of different issues with your existing code, so I'm just going to show you how it should look.

Note that ShellAboutA is the ASCII version of the function, ShellAboutW is the Unicode version. You can get C# to map it automatically, but it's best to specify it, and these day you should always use Unicode.

[DllImport("shell32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
public static extern int ShellAboutW(
    IntPtr hWnd,
    string szApp,
    string szOtherStuff,
    IntPtr hIcon);

You call it like this

ShellAboutW(IntPtr.Zero, "hello#whats up", null, IntPtr.Zero)

The first parameter is a Handle to a parent window, if necessary.

The last parameter is a Handle to an icon, if necessary. To use an icon, you can for example load it using GDI+.

using (var icon = new Icon(filePath))
{
    ShellAboutW(IntPtr.Zero, "hello#whats up", null, icon.Handle);
}

Upvotes: 1

Related Questions