Files
PDFReaderLite/pdfreaderlite/core/file_association.py
T

45 lines
1.3 KiB
Python

from __future__ import annotations
import sys
import winreg
from pathlib import Path
PROG_ID = "PDFReaderLite.pdf"
def current_launcher() -> str:
if getattr(sys, "frozen", False):
return f'"{Path(sys.executable)}" "%1"'
return f'"{Path(sys.executable)}" "{Path(sys.argv[0]).resolve()}" "%1"'
def register_pdf_association(icon_path: str | Path) -> None:
command = current_launcher()
icon = str(Path(icon_path))
with winreg.CreateKey(winreg.HKEY_CURRENT_USER, r"Software\Classes\.pdf") as key:
winreg.SetValueEx(key, "", 0, winreg.REG_SZ, PROG_ID)
with winreg.CreateKey(winreg.HKEY_CURRENT_USER, rf"Software\Classes\{PROG_ID}") as key:
winreg.SetValueEx(key, "", 0, winreg.REG_SZ, "PDFReaderLite PDF 文档")
with winreg.CreateKey(
winreg.HKEY_CURRENT_USER,
rf"Software\Classes\{PROG_ID}\DefaultIcon",
) as key:
winreg.SetValueEx(key, "", 0, winreg.REG_SZ, icon)
with winreg.CreateKey(
winreg.HKEY_CURRENT_USER,
rf"Software\Classes\{PROG_ID}\shell\open\command",
) as key:
winreg.SetValueEx(key, "", 0, winreg.REG_SZ, command)
def unregister_pdf_association() -> None:
try:
winreg.DeleteTree(winreg.HKEY_CURRENT_USER, rf"Software\Classes\{PROG_ID}")
except FileNotFoundError:
pass