在工作目录中使用环境变量创建快捷方式



目前我正在创建一个快捷方式:

SetShellVarContext all
SetOutPath "$INSTDIR"
CreateShortCut "$SMPROGRAMSMyApp.lnk" "$INSTDIRMyApp.exe"

我想把这个快捷方式的工作目录从C:Program FilesMyApp改为%UserProfile%

棘手的部分是,我不想扩展%UserProfile%,我想把它作为一个环境变量,所以程序在当前用户的概要文件目录中启动。

我可以通过NSIS实现这一点吗?如果没有,最简单的解决方法是什么?


参考:CreateShortcut

NSIS使用SetOutPath($OutDir)设置的路径在快捷方式上调用IShellLink::SetWorkingDirectory。

可以将$OutDir设置为无效路径,然后调用CreateShortcut:

Push $OutDir ; Save
StrCpy $OutDir "%UserProfile%"
CreateShortcut "$temptest1.lnk" "$sysdirCalc.exe"
Pop $OutDir ; Restore

它确实有效,但可能有点违反规则。你也可以在不依赖未记录的NSIS怪癖的情况下做到这一点:

!define CLSCTX_INPROC_SERVER 1
!define STGM_READWRITE 2
!define IID_IPersistFile {0000010b-0000-0000-C000-000000000046}
!define CLSID_ShellLink {00021401-0000-0000-c000-000000000046}
!define IID_IShellLinkA {000214ee-0000-0000-c000-000000000046}
!define IID_IShellLinkW {000214f9-0000-0000-c000-000000000046}
!ifdef NSIS_UNICODE
!define IID_IShellLink ${IID_IShellLinkW}
!else
!define IID_IShellLink ${IID_IShellLinkA}
!endif
!include LogicLib.nsh
Function Lnk_SetWorkingDirectory
Exch $9 ; New working directory 
Exch
Exch $8 ; Path
Push $0 ; HRESULT
Push $1 ; IShellLink
Push $2 ; IPersistFile
System::Call 'OLE32::CoCreateInstance(g "${CLSID_ShellLink}",i 0,i ${CLSCTX_INPROC_SERVER},g "${IID_IShellLink}",*i.r1)i.r0'
${If} $0 = 0
    System::Call `$1->0(g "${IID_IPersistFile}",*i.r2)i.r0`
    ${If} $0 = 0
        System::Call `$2->5(wr8,i${STGM_READWRITE})i.r0` ; Load
        ${If} $0 = 0
            System::Call `$1->9(tr9)i.r0` ; SetWorkingDirectory
            ${If} $0 = 0
                System::Call `$2->6(i0,i0)i.r0` ; Save
            ${EndIf}
        ${EndIf}
        System::Call `$2->2()` ; Release
    ${EndIf}
    System::Call `$1->2()` ; Release
${EndIf}
StrCpy $9 $0
Pop $1
Pop $0
Pop $8
Exch $9
FunctionEnd
Section
CreateShortcut "$temptest2.lnk" "$sysdirCalc.exe"
Push "$temptest2.lnk"
Push "%UserProfile%"
Call Lnk_SetWorkingDirectory 
Pop $0
DetailPrint HRESULT=$0 ; 0 = success
SectionEnd

需要注意的是,IShellLink::SetWorkingDirectory没有说明支持未扩展的环境变量,但它们似乎确实有效。

最新更新