Following a Shortcut: Part 2

As you may recall from part 1, this series of posts is about how to retrieve the target of a Windows shortcut (.lnk).
 
Now, I left off part 1 in C++ land, as I’d compiled a Win32 Dynamic Link Library which called the Windows Shell in order to extract a link’s target.
This article, which will be a tad shorter, I’ll focus on how I made use of the DLL in .Net, using interop.
 
First off, I created a static class called Win32.  In it I populated the following function signature:
[DllImport("ShortcutLib.dll", EntryPoint = "GetShortcutTarget", CharSet = CharSet.Unicode)]
public static extern string GetShortcutTarget(string pszFile, int cchMaxPath);
 
The function takes the same parameters as the C++ method, it’s really the attributes which play the biggest part of this code.
Remember, .Net deals in Unicode, so if you haven’t taken that into consideration when you write native (unmanaged C++) code, then best of luck to you.
 
If you recall, I did take this into account, so I can safely specify the CharSet, as well as the entrypoint and the DLL name.
The DLL will need to be either in the same location as the EXE file, or within the computer’s PATH.
 
If you want to verify that a method signature is correct in a native DLL, open it in Visual Studio.
Here’s how to do it:
1. Load up Visual Studio.  I’m using VS 2005 with Service Pack 1 and with the Vista Compatibility Patch (Beta).
2. Select File -> Open -> File
3. Browse to a DLL or EXE, select the file
4. Don’t click OK just yet.  Notice on the side of the Open button is a little arrow pointing down – click it
5. Select Open With.. -> Binary Editor
 
This brings up the PE file.  You can search for method signatures.  On older versions of Visual Studio the resource viewer was more robust and showed you neatly the export and import tables.
 
Luckily, Visual Studio also ships with a lovely tool called Depends, which allows you to see the import/export symbols.
 
You’ll likely find it here (VS 2005) as depends.exe:
%InstalledDrive%:\Program Files\Microsoft Visual Studio 9.0\Common7\Tools\Bin
Or a similar location for older versions.
 
Open the same DLL with depends, and you’ll see the following (see below):
Brilliant, the exported function is there (highlighted).
 
Now, back to C#… It’s so easy to use now..
 
string targetFilePath = Win32.GetShortcutTarget(sourceFilePath, 256);
if (File.Exists(targetFilePath))
{
      //do your worst!
}
Brilliant!
 
Third post will wrap it all up.
/Rob

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.