前言
如果想将你的程序注册到 window 的右键菜单,大家肯定知道改下注册表就完事了。但是怎么能实现程序在安装时候直接就注册到右键菜单呢?本文将实现将程序注册到右键菜单,并且将右键的文件夹地址带入到程序中。
效果如下
增加 installer.nsh 文件
installer.nsh 文件是用来辅助程序安装的,放在和 html 文件同级的目录即可,如 react 项目的 public 目录。
!macro preInit
; 安装位置设置
SetRegView 64
WriteRegExpandStr HKLM "${INSTALL_REGISTRY_KEY}" InstallLocation "D:\myapp"
WriteRegExpandStr HKCU "${INSTALL_REGISTRY_KEY}" InstallLocation "D:\myapp"
SetRegView 32
WriteRegExpandStr HKLM "${INSTALL_REGISTRY_KEY}" InstallLocation "D:\myapp"
WriteRegExpandStr HKCU "${INSTALL_REGISTRY_KEY}" InstallLocation "D:\myapp"
!macroend
!macro customInstall
; 注册右键菜单
WriteRegStr HKCR "Directory\Background\shell\myapp" "" "通过 myapp 打开"
WriteRegStr HKCR "Directory\Background\shell\myapp" "Icon" "D:\myapp\myapp.exe"
WriteRegStr HKCR "Directory\Background\shell\myapp\command" "" "D:\myapp\myapp.exe open %v%"
!macroend
!macro customUninstall
; 删除注册表
DeleteRegKey HKCR "Directory\Background\shell\myapp"
!macroend
第二条命令中 HKCR “Directory\Background\shell\ XXX” 这个名字起英文名字即可。
第三条命令中 open
用于在程序中辨别多个菜单项,%v%
是当前目录的变量。myapp
是你的程序名字。
注册表命令详细使用可参考最下面文档或者自行百度。
在 electron 代码中获取变量
我这里代码写到了主进程中。
const development = process.env.NODE_ENV === "development";
const mainWindow = new BrowserWindow({ xxx });
const arg1 = process.argv[1];
const arg2 = process.argv[2];
if (!development && arg1 === "open") {
// process.argv 第二个参数如果是 "open",那需要进行解析第三个参数(是一个项目地址)
console.log("文件夹:", arg2)
}
参考文档
nsis 文档 https://nsis.sourceforge.io/Docs/Chapter4.html#variables
electron builder https://www.electron.build/configuration/nsis#web-installer