Getting the desktop directory in Win32 application in Windows Vista

Posted: (EET/GMT+2)

 

Oftentimes, you need a way to find the correct location of the user's desktop, or any other special folder like Documents, Pictures, and so on. For years, this has been easy with Shell API functions such as SHGetFolderPath, but the thing is that this particular API is getting old. So old in fact, that beginning of Windows Vista (think Windows Server 2008 and forthcoming Windows 7 as well) this function is deprecated.

Thus, you need a better function, and in Vista an onwards it is called SHGetKnownFolderPath. Just lately, I needed to refresh an older Delphi application for Vista, and wanted to stop using deprecated APIs (a good idea more often than not). But of course (no surprise here), nobody had bothered to do the C language header translation for Delphi, so I had to do it myself (this is one reason I'm getting tired of Delphi, lack of cutting-edge API support). Here are the declarations you need, but remember that this only works on Vista and later.

Uses
  ComObj;

Type
  KNOWNFOLDERID    = TGUID;
  REFKNOWNFOLDERID = ^KNOWNFOLDERID;
  PWSTR            = PWideChar;
  PPWSTR           = ^PWSTR;

Const
  FOLDERID_Desktop : KNOWNFOLDERID =
    '{B4BFCC3A-DB2C-424C-B029-7FE99A87C641}';

Function SHGetKnownFolderPath(
  rfid : REFKNOWNFOLDERID; dwFlags : DWORD;
  hToken : THANDLE;
  var ppszPath : PPWSTR) : HRESULT; StdCall;
  External 'shell32.dll';
  
Procedure CoTaskMemFree(
  pv: Pointer); StdCall; External 'ole32.dll';

Now then, with the API declarations in place, it's easy to write functions such as GetDesktopPath:

function GetDesktopPath: String;
Var
  PathBuf   : PPWSTR;
  APIResult : HRESULT;

begin
  APIResult := SHGetKnownFolderPath(
    @FOLDERID_Desktop,0,0,PathBuf);
  OleCheck(APIResult);
  Result := WideCharToString(PWideChar(PathBuf));
  CoTaskMemFree(PathBuf);
end;

Of course, if you are a C/C++ developer, simply start using the SHGetKnownFolderPath API from the latest header files. And if .NET and/or C# programming is your call, then you already have System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop).

Keywords: HowTo, How to get desktop path, desktop directory, special folder location, shell folder.