Delphi – convert function to delphi 2010 (unicode)

delphidelphi-2010unicode

How to convert this function to Delphi 2010 (Unicode)?

function TForm1.GetTarget(const LinkFileName:String):String;
var
   //Link : String;
   psl  : IShellLink;
   ppf  : IPersistFile;
   WidePath  : Array[0..260] of WideChar;
   Info      : Array[0..MAX_PATH] of Char;
   wfs       : TWin32FindData;
begin
  if UpperCase(ExtractFileExt(LinkFileName)) <> '.LNK' Then
  begin
    Result:='NOT a shortuct by extension!';
    Exit;
  end;

  CoCreateInstance(CLSID_ShellLink, nil, CLSCTX_INPROC_SERVER, IShellLink, psl);
  if psl.QueryInterface(IPersistFile, ppf) = 0 Then
  Begin
    MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, PAnsiChar(LinkFileName), -1, @WidePath, MAX_PATH);
    ppf.Load(WidePath, STGM_READ);
    psl.GetPath((@info), MAX_PATH, wfs, SLGP_UNCPRIORITY);
    Result := info;

  end
  else
    Result := '';
end;

Thanks

Best Answer

As far as I can tell, ppf.Load should be able to just take your LinkFileName directly with a cast to PChar (which is now PWideChar). Removing the MultiByteToWideChar line and using PChar(LinkFileName) instead of copying to a temporary variable should do it.

This would make the code look like this:

function TForm1.GetTarget(const LinkFileName:String):String;
var
   //Link : String;
   psl  : IShellLink;
   ppf  : IPersistFile;
   //WidePath  : Array[0..260] of WideChar;
   Info      : Array[0..MAX_PATH] of Char;
   wfs       : TWin32FindData;
begin
  if UpperCase(ExtractFileExt(LinkFileName)) <> '.LNK' Then
  begin
    Result:='NOT a shortuct by extension!';
    Exit;
  end;

  CoCreateInstance(CLSID_ShellLink, nil, CLSCTX_INPROC_SERVER, IShellLink, psl);
  if psl.QueryInterface(IPersistFile, ppf) = 0 Then
  Begin
    ppf.Load(PChar(LinkFileName), STGM_READ);
    psl.GetPath((@info), MAX_PATH, wfs, SLGP_UNCPRIORITY);
    Result := info;    
  end
  else
    Result := '';
end;

psl.GetPath is declared as using a LPTSTR in MSDN, so I believe you should get the Unicode version without changing that part.