采用globalShortcut,是主进程
ps:快捷键方式是全局的‘即使应用程序没有键盘焦点,它也仍然在持续监听键盘事件。在app模块的ready事件就绪之前,这个模块不能使用。
import {
app,
BrowserWindow,
ipcMain,
globalShortcut,
} from "electron";
// 主窗口函数
createMainWindow() {
globalShortcut.register("ctrl+F5", () => {
app.relaunch();
app.exit();
});
globalShortcut.register("ctrl+F4", () => {
this.mainWindow?.reload();
});
globalShortcut.register("ctrl+F6", () => {
app.exit();
});
globalShortcut.register("F11", () => {
// 是否全屏
if (this.mainWindow?.isFullScreen()) {
// this.mainWindow?.minimize();
this.mainWindow?.setFullScreen(false);
this.mainWindow?.setMenuBarVisibility(true);
} else {
this.mainWindow?.setFullScreen(true);
this.mainWindow?.setMenuBarVisibility(false);
}
});
globalShortcut.register("ctrl+F12", () => {
this.mainWindow?.webContents.openDevTools({ mode: "detach" });
});
}
app.on('will-quit', () => {
// 注销快捷键
globalShortcut.unregister('CommandOrControl+X')
// 注销所有快捷键
globalShortcut.unregisterAll()
})
在主进程实现
electron加入开机启动项最核心的代码是:
app.setLoginItemSettings();
function onAppReady() {
new InitWindow().initWindow();
// 设置开机自起
const exeName = path.basename(process.execPath);
app.setLoginItemSettings({
// 设置为true注册开机自起
openAtLogin: false, /
openAsHidden: false, //macOs
path: process.execPath,
args: ["--processStart", `"${exeName}"`],
});
}
app.isReady() ? onAppReady() : app.on("ready", onAppReady);
settings是个object类型,其key有:
args: ["--openAsHidden"]
设置开机启动时,在args
中传入--openAsHidden
,这个字符串可以随便更改。获取开机启动时,也要在args
中传入同样的字符串,不然获取不到正确的值。
然后在显示主窗口时,先判断一下
process.argv
中是否包含--openAsHidden
,如果包含,说明是开机自动启动的,这时候不显示窗口;相反 如果不包含--openAsHidden
的话,说明是用户手动启动软件,这时正常显示窗口就好了:
win.once("ready-to-show", () => {
if (process.argv.indexOf("--openAsHidden") < 0)
win.show();
});
如果需要在 Windows 上使用Squirrel的 autoUpdater
,你需要将启动路径设置为 Update.exe,并传递指定应用程序名称的参数。 例如:
const appFolder = path.dirname(process.execPath)
const updateExe = path.resolve(appFolder, '..', 'Update.exe')
const exeName = path.basename(process.execPath)
app.setLoginItemSettings({
openAtLogin: true,
path: updateExe,
args: [
'--processStart', `"${exeName}"`,
'--process-start-args', `"--hidden"`
]
})