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

时间:2015-11-28 15:07:01

标签: installation installer install nsis shortcut

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

SetShellVarContext all
SetOutPath "$INSTDIR"
CreateShortCut "$SMPROGRAMS\MyApp.lnk" "$INSTDIR\MyApp.exe"

我想将此快捷方式的工作目录从C:\Program Files\MyApp更改为%UserProfile%

棘手的部分是我不希望扩展%UserProfile%,我想将它保留为环境变量,因此程序在当前用户的配置文件目录中启动。

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


参考:CreateShortcut

1 个答案:

答案 0 :(得分:2)

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

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

Push $OutDir ; Save
StrCpy $OutDir "%UserProfile%"
CreateShortcut "$temp\test1.lnk" "$sysdir\Calc.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 "$temp\test2.lnk" "$sysdir\Calc.exe"
Push "$temp\test2.lnk"
Push "%UserProfile%"
Call Lnk_SetWorkingDirectory 
Pop $0
DetailPrint HRESULT=$0 ; 0 = success
SectionEnd

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