将函数转换为delphi 2010(unicode)

时间:2009-11-25 14:50:19

标签: delphi unicode delphi-2010

如何将此功能转换为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;

谢谢

2 个答案:

答案 0 :(得分:1)

据我所知,ppf.Load应该能够直接将你的LinkFileName带到PChar(现在是PWideChar)。删除MultiByteToWideChar行并使用PChar(LinkFileName)而不是复制到临时变量应该这样做。

这会使代码看起来像这样:

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在MSDN中被声明为使用LPTSTR,因此我相信您应该在不更改该部分的情况下获取Unicode版本。

答案 1 :(得分:1)

我对Michael的答案做了一些更改,使用正确的字符串转换为大写,检查错误情况并删除不必要的东西:

function TForm1.GetTarget(const LinkFileName: String): String;
var
  psl: IShellLink;
  ppf: IPersistFile;
  wfs: TWin32FindData;
begin
  if Character.ToUpper(ExtractFileExt(LinkFileName)) <> '.LNK' Then
    Exit('NOT a shortcut by extension!');

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