Why to avoid ShellExecute!

ShellExecute() is a silly function. It still exists to allow for backwards compatibility with Systems before Windows 95. It is ridiculous to use it, while another function with a superset of functionality exists already: ShellExecuteEx(). To name just the biggest disadvantage of ShellExecute(): it prevents proper localization. The error messages are given in English only, while any error message should be shown to the user in the system’s language. Furthermore this function does not allow to map to system error codes (those you could determine via GetLastError()). As I mentioned, it’s just silly. You can get a cleaner implementation using ShellExecuteEx() and providing an interface similar to the quasi-deprecated function:

BOOL ShellExecuteNoThrow(
		HWND hwnd,
		LPCTSTR lpVerb,
		LPCTSTR lpFile,
		LPCTSTR lpParameters,
		LPCTSTR lpDirectory,
		INT nShowCmd)
{
	SHELLEXECUTEINFO sei = {
		sizeof(SHELLEXECUTEINFO),
		0,
		hwnd,
		lpVerb,
		lpFile,
		lpParameters,
		lpDirectory,
		nShowCmd,
		0, // hInstApp
		0,
		0,
		0,
		0, // dwHotKey
		0,
		0
		};

	return ShellExecuteEx(&sei);
}

Why do I write this? Well, I know too many friends of the “good old” function …

If you need the Delphi version you might resort to this very old implementation of mine. It even allows to wait for the created process to finish. Something that most people used to implement via CreateProcess()

// Oliver

BTW: The above implementation is what I wrote for WinDirStat, you may freely use it though. Since I am the user I have all rights and put it into the public domain.

This entry was posted in Programming. Bookmark the permalink.

One Response to Why to avoid ShellExecute!

  1. Oliver says:

    Oh, because I got feedback off-the-blog. Yes, it is right that on newer versions of Windows GetLastError() will give you the correct error codes. However, due to the fact that this is not documented nor verified on older versions, you should not rely on it.

Leave a Reply

Your email address will not be published. Required fields are marked *