From 5428beb6dbb785a8806d09e4a1b3d2d44af0ae2e Mon Sep 17 00:00:00 2001 From: thzxx Date: Mon, 18 May 2026 15:10:28 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E5=8D=95=E5=AE=9E=E4=BE=8B=E9=94=81?= =?UTF-8?q?=EF=BC=8C=E5=8F=8C=E5=87=BBmd=E6=96=87=E4=BB=B6=E5=9C=A8?= =?UTF-8?q?=E5=B7=B2=E6=9C=89=E7=AA=97=E5=8F=A3=E6=89=93=E5=BC=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 添加 requestSingleInstanceLock() 防止重复启动 - second-instance 事件中提取文件路径,转发给已有窗口 - 复用 getFilePathFromArgs() 解析命令行参数 --- main.js | 44 +++++++++++++++++++++++++++++++++++++------- 1 file changed, 37 insertions(+), 7 deletions(-) diff --git a/main.js b/main.js index 86d3d24..7e32490 100644 --- a/main.js +++ b/main.js @@ -8,6 +8,41 @@ let pendingFilePath = null; let fileWatcher = null; let closeTimeout = null; +// ===== Single Instance Lock ===== +const gotTheLock = app.requestSingleInstanceLock(); + +if (!gotTheLock) { + app.quit(); +} else { + app.on('second-instance', (event, commandLine, workingDirectory) => { + // A second instance was launched (e.g. double-clicking a .md file) + // Focus the existing window and open the file in it + if (mainWindow) { + if (mainWindow.isMinimized()) mainWindow.restore(); + mainWindow.focus(); + + // Extract file path from the second instance's command line args + const filePath = getFilePathFromArgs(commandLine); + if (filePath) { + openFileInTab(filePath); + } + } + }); +} + +// Extract a valid file path from command line arguments (skip Electron flags) +function getFilePathFromArgs(args) { + for (let i = 1; i < args.length; i++) { + const arg = args[i]; + if (!arg.startsWith('--') && !arg.startsWith('-')) { + try { + if (fs.existsSync(arg)) return arg; + } catch (e) { /* ignore */ } + } + } + return null; +} + function createWindow() { mainWindow = new BrowserWindow({ width: 1200, @@ -252,14 +287,9 @@ ipcMain.handle('window:cancelClose', () => { } }); -// Command line file +// Command line file (first instance) function getCommandLineFile() { - const args = process.argv.slice(1); - if (args.length > 0 && !args[0].startsWith('--')) { - const filePath = args[0]; - if (fs.existsSync(filePath)) return filePath; - } - return null; + return getFilePathFromArgs(process.argv); } // App lifecycle