import os import winreg import logging from pathlib import Path import uuid class CursorRegistry: """Cursor注册表操作工具类""" def __init__(self): self.cursor_path = Path(os.path.expanduser("~")) / "AppData" / "Local" / "Programs" / "Cursor" self.app_path = self.cursor_path / "resources" / "app" self.machine_guid_path = r"SOFTWARE\Microsoft\Cryptography" self.machine_guid_name = "MachineGuid" def refresh_registry(self) -> bool: """刷新注册表 Returns: bool: 是否成功 """ try: # 生成新的GUID new_guid = str(uuid.uuid4()) # 修改 MachineGuid try: with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, self.machine_guid_path, 0, winreg.KEY_ALL_ACCESS) as key: winreg.SetValueEx(key, self.machine_guid_name, 0, winreg.REG_SZ, new_guid) logging.info(f"更新 MachineGuid 成功: {new_guid}") except Exception as e: logging.error(f"更新 MachineGuid 失败: {str(e)}") return False # 获取Cursor安装路径 cursor_exe = self.cursor_path / "Cursor.exe" if not cursor_exe.exists(): logging.error("未找到Cursor.exe") return False # 刷新注册表项 try: # 打开HKEY_CURRENT_USER\Software\Classes\Directory\Background\shell\Cursor key_path = r"Software\Classes\Directory\Background\shell\Cursor" with winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_path, 0, winreg.KEY_WRITE) as key: winreg.SetValueEx(key, "Icon", 0, winreg.REG_SZ, str(cursor_exe)) # 打开command子键 with winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_path + r"\command", 0, winreg.KEY_WRITE) as key: winreg.SetValueEx(key, "", 0, winreg.REG_SZ, f'"{str(cursor_exe)}" "%V"') logging.info("注册表刷新成功") return True except WindowsError as e: logging.error(f"刷新注册表失败: {str(e)}") return False except Exception as e: logging.error(f"刷新注册表失败: {str(e)}") return False def clean_registry(self) -> bool: """清理Cursor相关的注册表项 Returns: bool: 是否成功 """ try: # 删除注册表项 try: key_path = r"Software\Classes\Directory\Background\shell\Cursor" winreg.DeleteKey(winreg.HKEY_CURRENT_USER, key_path + r"\command") winreg.DeleteKey(winreg.HKEY_CURRENT_USER, key_path) logging.info("注册表清理成功") return True except WindowsError as e: if e.winerror == 2: # 找不到注册表项 logging.info("注册表项不存在,无需清理") return True logging.error(f"清理注册表失败: {str(e)}") return False except Exception as e: logging.error(f"清理注册表过程出错: {str(e)}") return False