electron 使用ipcMain.handle 和ipcMain.invoke 发现中文路径乱码,同时下载了windows-shortcuts 进行解析路径,发现还是乱码
解决办法:1.将windows-shortcuts里面的Shortcut.exe文件复制到根目录,同时在electron--main.ts下编写代码
/**
- 解析 Shortcut.exe 的输出结果
*/
function parseQuery(stdout: string): {
target?: string;
args?: string;
workingDir?: string;
runStyle?: number;
icon?: string;
iconIndex?: string;
hotkey?: number;
desc?: string;
expanded: {
target?: string;
args?: string;
workingDir?: string;
icon?: string;
};
} {
const result: any = {
expanded: {},
};
const lines = stdout.split(/[\r\n]+/);
for (const line of lines) {
if (!line.includes('=')) continue;
const [key, value] = line.split('=', 2);
switch (key) {
case 'TargetPath':
result.target = value;
break;
case 'TargetPathExpanded':
result.expanded.target = value;
break;
case 'Arguments':
result.args = value;
break;
case 'ArgumentsExpanded':
result.expanded.args = value;
break;
case 'WorkingDirectory':
result.workingDir = value;
break;
case 'WorkingDirectoryExpanded':
result.expanded.workingDir = value;
break;
case 'RunStyle':
result.runStyle = parseInt(value);
break;
case 'IconLocation': {
const [iconPath, iconIndex] = value.split(',');
result.icon = iconPath;
result.iconIndex = iconIndex;
break;
}
case 'IconLocationExpanded': {
const [iconPath] = value.split(',');
result.expanded.icon = iconPath;
break;
}
case 'HotKey': {
const match = value.match(/\d+/);
if (match) result.hotkey = parseInt(match[0]);
break;
}
case 'Description':
result.desc = value;
break;
}
}
// fallback 逻辑:如果 expanded 属性缺失,补全它
for (const key of ['target', 'args', 'workingDir', 'icon']) {
if (!result.expanded[key]) {
result.expanded[key] = result[key];
}
}
return result;
}
/**
- 处理解析 lnk 文件的请求
*/
ipcMain.handle('resolve-lnk', async (_event, lnkPath: string) => {
const shortcutExePath = isDev
? path.join(__dirname, '../native/Shortcut.exe') // 开发环境路径
: path.join(process.resourcesPath, 'native/Shortcut.exe'); // 打包后路径
// 直接使用 lnkPath,不展开环境变量
const args = ['/A:Q',/F:${lnkPath}];
return new Promise((resolve, reject) => {
execFile(shortcutExePath, args, { encoding: 'buffer' }, (error, stdout, stderr) => {
if (error) {
console.error('[Shortcut.exe Error]', error);
reject(stderr || stdout || error.message);
return;
}
try {
const output = iconv.decode(stdout, 'gbk');
console.log('[Shortcut Output]', output);
const result = parseQuery(output);
resolve(result);
} catch (e: any) {
reject('解析失败: ' + e.message);
}
});
});
});
输出的就是中文的,需要打开exe文件的
function executeExe(exePath: string): Promise<string> {
return new Promise(async (resolve, reject) => {
try {
const result = await shell.openPath(exePath);
if (result) {
reject(执行失败: ${result});
} else {
resolve('启动成功');
}
} catch (err: any) {
reject(执行出错: ${err.message});
}
});
}