wps_handle.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import os
  2. import time
  3. import pythoncom
  4. import win32com
  5. import win32com.client
  6. import win32con
  7. import win32gui
  8. from win10toast import ToastNotifier
  9. from tools.check import is_file_open_in_wps
  10. from tools.config import file_type_map
  11. toaster = ToastNotifier()
  12. def bring_wps_window_to_front(file_path: str) -> bool:
  13. '''
  14. 找到文件被打开的窗口置顶,目前实现方式会被windows安全程序拦截只会在控制栏闪烁窗口图标
  15. :param file_path:
  16. :return:
  17. '''
  18. # abs_path = os.path.abspath(file_path).lower()
  19. # suffix = file_path.split('.')[-1]
  20. #
  21. # try:
  22. # pythoncom.CoInitialize()
  23. # app = win32com.client.GetActiveObject(file_type_map[suffix][0])
  24. # for wb in getattr(app, file_type_map[suffix][1]):
  25. # if wb.FullName.lower() == abs_path:
  26. # hwnd = app.Hwnd # WPS 主窗口句柄
  27. # if hwnd:
  28. # win32gui.ShowWindow(hwnd, win32con.SW_RESTORE) # 恢复最小化窗口
  29. # win32gui.SetForegroundWindow(hwnd) # 置顶窗口
  30. # return True
  31. # except Exception as e:
  32. # print("置顶失败:", e)
  33. # return False
  34. # finally:
  35. # pythoncom.CoUninitialize()
  36. # return False
  37. return True
  38. def get_active_wps_text():
  39. pythoncom.CoInitialize() # 初始化 COM
  40. try:
  41. wps = win32com.client.Dispatch("Kwps.Application") # WPS Word
  42. doc = wps.ActiveDocument
  43. content = doc.Content.Text
  44. print("[WPS] 当前文档内容:", content[:100]) # 打印前100个字符
  45. return content
  46. except Exception as e:
  47. print("[!] 无法访问 WPS 文档:", e)
  48. return None
  49. def check_for_changes():
  50. global current_text
  51. while True:
  52. time.sleep(2) # 每2秒检查一次文档内容
  53. new_text = get_active_wps_text()
  54. if new_text and new_text != current_text:
  55. current_text = new_text
  56. update_recommendation(new_text)
  57. toaster.show_toast("新推荐内容", recommendation, duration=10)
  58. def update_recommendation(content):
  59. global recommendation
  60. recommendation = f"基于你输入的内容,推荐:{content[:50]}..."
  61. if __name__ == '__main__':
  62. if is_file_open_in_wps('storage/接口文档.txt'):
  63. bring_wps_window_to_front('storage/接口文档.txt')
  64. bring_wps_window_to_front('storage/接口文档.txt')