如何使用GDScript为指定.exe文件创建桌面快捷方式
在Godot中用GDScript创建Windows桌面快捷方式
以下是接收.exe文件路径作为输入,自动在桌面创建对应快捷方式的GDScript函数:
func create_desktop_shortcut(exe_path: String) -> bool: # 检查目标exe文件是否存在 if not FileAccess.file_exists(exe_path): print("错误:指定的exe文件不存在") return false # 获取桌面路径 var desktop_path = OS.get_special_dir(OS.SPECIAL_DIR_DESKTOP) # 从exe路径提取文件名(不含后缀)作为快捷方式名称 var shortcut_name = Paths.get_file_name_without_extension(exe_path) + ".lnk" var shortcut_path = Paths.join(desktop_path, shortcut_name) # 构造PowerShell命令,用于创建快捷方式 var ps_command = """ $WshShell = New-Object -ComObject WScript.Shell $shortcut = $WshShell.CreateShortcut('%s') $shortcut.TargetPath = '%s' $shortcut.Save() """ % [shortcut_path.replace("'", "''"), exe_path.replace("'", "''")] # 执行PowerShell命令 var exit_code = OS.execute("powershell", ["-Command", ps_command], true) if exit_code == 0: print("快捷方式已创建:", shortcut_path) return true else: print("创建快捷方式失败,错误码:", exit_code) return false
关键点说明:
- 文件有效性校验:先验证输入的exe路径是否存在,避免无效操作
- 桌面路径获取:使用
OS.get_special_dir(OS.SPECIAL_DIR_DESKTOP)确保适配不同Windows版本的桌面路径 - 路径转义处理:将路径中的单引号替换为双单引号,避免PowerShell解析命令时因特殊字符/空格报错
- 系统原生方法:借助Windows自带的WScript.Shell COM对象创建快捷方式,是稳定可靠的系统级实现
使用示例:
# 替换为你的实际exe路径 create_desktop_shortcut("C:/Program Files/MyApp/MyApp.exe")
内容的提问来源于stack exchange,提问作者stepic Game
相关产品推荐
相关产品推荐

