Auto-uninstall old before installing new: Difference between revisions

From NSIS Wiki
Jump to navigationJump to search
(missing done goto label)
(Suggested code that does not assume previous install was in the default directory)
Line 40: Line 40:
   Exec $INSTDIR\uninst.exe ; instead of the ExecWait line
   Exec $INSTDIR\uninst.exe ; instead of the ExecWait line
</highlight-nsis>
</highlight-nsis>
NOTE:  Both previous methods assume the program was installed in the default directory, which may not be correct.  Here's what I use:
<highlight-nsis>
  uninst:
    ClearErrors
    Exec $R0
  done:
</highlight-nsis>


[[Category:System Related Functions]]
[[Category:System Related Functions]]

Revision as of 20:14, 7 July 2017

Author: codehistorian (talk, contrib)


This is a code snippet you can put into your .onInit function that will detect whether your software is already installed and, if so, allows the user to uninstall it first.

In the source below, we use the define ${PROGRAM_NAME} to be the name of the product as well as the name of the installer/uninstaller. You can either define this define or search/replace it. If you name your uninstaller or registry location differently, you should change those strings accordingly.

Function .onInit
 
  ReadRegStr $R0 HKLM \
  "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PROGRAM_NAME}" \
  "UninstallString"
  StrCmp $R0 "" done
 
  MessageBox MB_OKCANCEL|MB_ICONEXCLAMATION \
  "${PROGRAM_NAME} is already installed. $\n$\nClick `OK` to remove the \
  previous version or `Cancel` to cancel this upgrade." \
  IDOK uninst
  Abort
 
;Run the uninstaller
uninst:
  ClearErrors
  ExecWait '$R0 _?=$INSTDIR' ;Do not copy the uninstaller to a temp file
 
  IfErrors no_remove_uninstaller done
    ;You can either use Delete /REBOOTOK in the uninstaller or add some code
    ;here to remove the uninstaller. Use a registry key to check
    ;whether the user has chosen to uninstall. If you are using an uninstaller
    ;components page, make sure all sections are uninstalled.
  no_remove_uninstaller:
 
done:
 
FunctionEnd

The following variant lets the uninstaller remove itself, so the IfErrors block is not needed any more:

  Exec $INSTDIR\uninst.exe ; instead of the ExecWait line

NOTE: Both previous methods assume the program was installed in the default directory, which may not be correct. Here's what I use:

  uninst:
    ClearErrors
    Exec $R0
  done: