fix: 单实例锁,双击md文件在已有窗口打开

- 添加 requestSingleInstanceLock() 防止重复启动
- second-instance 事件中提取文件路径,转发给已有窗口
- 复用 getFilePathFromArgs() 解析命令行参数
This commit is contained in:
thzxx
2026-05-18 15:10:28 +08:00
parent 07989db28e
commit 5428beb6db
+37 -7
View File
@@ -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