Advertisement
Python253

win_shortcuts_automation

May 21st, 2024
726
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 18.07 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Filename: win_shortcuts_automation.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. :: Welcome to Windows Shortcuts Automation ::
  9.  
  10.    - This script is your gateway to unlocking the true potential of your Windows experience!
  11.    - Say goodbye to repetitive tasks and hello to seamless automation with Python.
  12.    - Whether you're a seasoned user looking to supercharge your workflow or a curious beginner eager to explore the possibilities,
  13.      this script is here to revolutionize the way you interact with your Windows system.
  14.  
  15. Features:
  16.    - Harness the power of Python to automate a plethora of Windows shortcuts effortlessly.
  17.    - Enjoy a user-friendly interface that simplifies the selection and execution of shortcuts.
  18.    - Customize your experience by crafting your own personalized hotkeys to suit your unique needs.
  19.  
  20. Prerequisites:
  21.    - Python 3.x
  22.    - The following modules must be installed:
  23.        - pygetwindow
  24.        - PyAutoGUI
  25.        - keyboard
  26.        - json
  27.        - os
  28.  
  29. How to Use:
  30.    1. Ensure you have Python 3.x installed on your system.
  31.    2. Install the required modules using pip:
  32.    
  33.        'pip install pyautogui pygetwindow keyboard json'
  34.        
  35.    3. Run the script and embark on an adventure of Windows automation!
  36.       - Simply follow the on-screen prompts to select and execute your desired shortcuts.
  37.  
  38. Additional Insights:
  39.    - Certain shortcuts may necessitate additional permissions or configurations, so be sure to grant any required permissions.
  40.    - Delve into the realm of Windows automation with confidence and unleash your productivity like never before!
  41. """
  42.  
  43. # Get Essential Imports
  44. import json
  45. import keyboard
  46. import os
  47. import pyautogui
  48. import pygetwindow as gw
  49.  
  50. def select_program():
  51.     """
  52.    Function for program selection via file explorer navigation
  53.    """
  54.     os.system("explorer C:\\Program Files (x86)")
  55.    
  56. # Predefined hotkeys
  57. PREDEFINED_HOTKEYS = {
  58.     "open_start_menu": ['win'],
  59.     "open_secret_start_menu": ['win', 'x'],
  60.     "cycle_through_taskbar": ['win', 't'],
  61.     "go_to_nth_application": ['win', '[n]'],
  62.     "show_all_running_applications": ['win', 'tab'],
  63.     "show_hide_desktop": ['win', 'd'],
  64.     "minimize_all_windows": ['ctrl', 'm'],
  65.     "temporary_show_desktop": ['win', ','],
  66.     "magnify_screen_content": ['win', 'plus'],
  67.     "maximize_window": ['win', 'up'],
  68.     "maximize_window_vertically": ['win', 'shift', 'up'],
  69.     "move_window_to_left_monitor": ['custom'],
  70.     "move_window_to_right_monitor": ['custom'],
  71.     "take_rectangular_screenshot": ['win', 'shift', 's'],
  72.     "take_full_screenshot": ['win', 'printscreen'],
  73.     "create_new_virtual_desktop": ['win', 'ctrl', 'd'],
  74.     "move_between_virtual_desktops_left": ['win', 'ctrl', 'left'],
  75.     "move_between_virtual_desktops_right": ['win', 'ctrl', 'right'],
  76.     "close_current_virtual_desktop": ['win', 'ctrl', 'f4'],
  77.     "open_action_center": ['win', 'a'],
  78.     "open_search": ['win', 's'],
  79.     "open_new_edge_tab": ['win', 'c'],
  80.     "open_windows_settings": ['win', 'i'],
  81.     "connect_sidebar": ['win', 'k'],
  82.     "use_voice_typing": ['win', 'h'],
  83.     "lock_computer": ['win', 'l'],
  84.     "lock_screen_orientation": ['win', 'o'],
  85.     "open_presentation_sidebar": ['win', 'p'],
  86.     "open_ease_of_access_center": ['win', 'u'],
  87.     "select_from_clipboard_history": ['win', 'v'],
  88.     "set_focus_to_notification_area": ['win', 'b'],
  89.     "open_emoji_panel": ['win', '.'],
  90.     "start_stop_narrator": ['win', 'ctrl', 'enter'],
  91.     "quick_language_list": ['win', 'space'],
  92.     "open_system_control_panel": ['win', 'pause'],
  93.     "start_task_manager": ['ctrl', 'shift', 'esc'],
  94.     "start_on_screen_keyboard": ['ctrl', 'win', 'o'],
  95.     "open_office_application_w": ['ctrl', 'shift', 'alt', 'win', 'w'],
  96.     "open_office_application_p": ['ctrl', 'shift', 'alt', 'win', 'p'],
  97.     "open_office_application_x": ['ctrl', 'shift', 'alt', 'win', 'x'],
  98.     "open_office_application_o": ['ctrl', 'shift', 'alt', 'win', 'o'],
  99.     "open_office_application_t": ['ctrl', 'shift', 'alt', 'win', 't'],
  100.     "open_office_application_d": ['ctrl', 'shift', 'alt', 'win', 'd'],
  101.     "open_office_application_n": ['ctrl', 'shift', 'alt', 'win', 'n'],
  102.     "open_office_application_l": ['ctrl', 'shift', 'alt', 'win', 'l'],
  103.     "open_office_application_y": ['ctrl', 'shift', 'alt', 'win', 'y'],
  104.     "open_calculator": ['win', 'r', 'c', 'a', 'l', 'c', 'enter']
  105. }
  106.    
  107. """ :: Function definitions for shortcuts :: """
  108.  
  109. def open_start_menu():
  110.     """
  111.    Opens the Start Menu.
  112.    """
  113.     pyautogui.hotkey('win')
  114.  
  115. def open_secret_start_menu():
  116.     """
  117.    Opens the secret Start Menu.
  118.    """
  119.     pyautogui.hotkey('win', 'x')
  120.  
  121. def cycle_through_taskbar():
  122.     """
  123.    Cycles through the items on the taskbar.
  124.    """
  125.     pyautogui.hotkey('win', 't')
  126.  
  127. def go_to_nth_application():
  128.     """
  129.    Goes to the nth application on the taskbar.
  130.    """
  131.     n = input("Enter application number (1-9): ")
  132.     pyautogui.hotkey('win', n)
  133.  
  134. def show_all_running_applications():
  135.     """
  136.    Shows all running applications using Task View.
  137.    """
  138.     pyautogui.hotkey('win', 'tab')
  139.  
  140. def show_hide_desktop():
  141.     """
  142.    Shows or hides the desktop.
  143.    """
  144.     pyautogui.hotkey('win', 'd')
  145.  
  146. def minimize_all_windows():
  147.     """
  148.    Minimizes all open windows.
  149.    """
  150.     pyautogui.hotkey('ctrl', 'm')
  151.  
  152. def temporary_show_desktop():
  153.     """
  154.    Temporarily shows the desktop.
  155.    """
  156.     pyautogui.hotkey('win', ',')
  157.  
  158. def magnify_screen_content():
  159.     """
  160.    Magnifies the content on the screen.
  161.    """
  162.     pyautogui.hotkey('win', 'plus')
  163.  
  164. def maximize_window():
  165.     """
  166.    Maximizes the current window.
  167.    """
  168.     pyautogui.hotkey('win', 'up')
  169.  
  170. def maximize_window_vertically():
  171.     """
  172.    Maximizes the height of the current window.
  173.    """
  174.     pyautogui.hotkey('win', 'shift', 'up')
  175.  
  176. def move_window_to_left_monitor():
  177.     """
  178.    Moves the current window to the left monitor.
  179.    """
  180.     active_window = gw.getActiveWindow()
  181.     if active_window:
  182.         active_window.moveTo(0, active_window.top)
  183.    
  184. def move_window_to_right_monitor():
  185.     """
  186.    Moves the current window to the right monitor.
  187.    """
  188.     active_window = gw.getActiveWindow()
  189.     if active_window:
  190.         screen_width, _ = pyautogui.size()
  191.         window_width, _ = active_window.size
  192.         new_left_position = min(screen_width - window_width, active_window.left + screen_width)
  193.         active_window.move(new_left_position, active_window.top)
  194.  
  195. def take_rectangular_screenshot():
  196.     """
  197.    Takes a rectangular screenshot.
  198.    """
  199.     pyautogui.hotkey('win', 'shift', 's')
  200.  
  201. def take_full_screenshot():
  202.     """
  203.    Takes a full screenshot.
  204.    """
  205.     pyautogui.hotkey('win', 'printscreen')
  206.  
  207. def create_new_virtual_desktop():
  208.     """
  209.    Creates a new virtual desktop.
  210.    """
  211.     pyautogui.hotkey('win', 'ctrl', 'd')
  212.  
  213. def move_between_virtual_desktops(direction):
  214.     """
  215.    Moves between virtual desktops.
  216.  
  217.    Args:
  218.        direction (str): The direction to move between desktops. Can be 'left' or 'right'.
  219.    """
  220.     pyautogui.hotkey('win', 'ctrl', direction)
  221.  
  222. def close_current_virtual_desktop():
  223.     """
  224.    Closes the current virtual desktop.
  225.    """
  226.     pyautogui.hotkey('win', 'ctrl', 'f4')
  227.  
  228. def open_action_center():
  229.     """
  230.    Opens the Action Center.
  231.    """
  232.     pyautogui.hotkey('win', 'a')
  233.  
  234. def open_search():
  235.     """
  236.    Opens the search menu.
  237.    """
  238.     pyautogui.hotkey('win', 's')
  239.  
  240. def open_new_edge_tab():
  241.     """
  242.    Opens a new tab in Microsoft Edge.
  243.    """
  244.     pyautogui.hotkey('win', 'c')
  245.  
  246. def open_windows_settings():
  247.     """
  248.    Opens the Windows Settings.
  249.    """
  250.     pyautogui.hotkey('win', 'i')
  251.  
  252. def connect_sidebar():
  253.     """
  254.    Connects the sidebar.
  255.    """
  256.     pyautogui.hotkey('win', 'k')
  257.  
  258. def use_voice_typing():
  259.     """
  260.    Starts voice typing.
  261.    """
  262.     pyautogui.hotkey('win', 'h')
  263.  
  264. def lock_computer():
  265.     """
  266.    Locks the computer.
  267.    """
  268.     pyautogui.hotkey('win', 'l')
  269.  
  270. def lock_screen_orientation():
  271.     """
  272.    Locks the screen orientation.
  273.    """
  274.     pyautogui.hotkey('win', 'o')
  275.  
  276. def open_presentation_sidebar():
  277.     """
  278.    Opens the presentation sidebar.
  279.    """
  280.     pyautogui.hotkey('win', 'p')
  281.  
  282. def open_ease_of_access_center():
  283.     """
  284.    Opens the Ease of Access Center.
  285.    """
  286.     pyautogui.hotkey('win', 'u')
  287.  
  288. def select_from_clipboard_history():
  289.     """
  290.    Selects from the clipboard history.
  291.    """
  292.     pyautogui.hotkey('win', 'v')
  293.  
  294. def set_focus_to_notification_area():
  295.     """
  296.    Sets focus to the notification area.
  297.    """
  298.     pyautogui.hotkey('win', 'b')
  299.  
  300. def open_emoji_panel():
  301.     """
  302.    Opens the emoji panel.
  303.    """
  304.     pyautogui.hotkey('win', '.')
  305.  
  306. def start_stop_narrator():
  307.     """
  308.    Starts or stops the narrator.
  309.    """
  310.     pyautogui.hotkey('win', 'ctrl', 'enter')
  311.  
  312. def quick_language_list():
  313.     """
  314.    Opens the quick language list.
  315.    """
  316.     pyautogui.hotkey('win', 'space')
  317.  
  318. def open_system_control_panel():
  319.     """
  320.    Opens the system control panel.
  321.    """
  322.     pyautogui.hotkey('win', 'pause')
  323.  
  324. def start_task_manager():
  325.     """
  326.    Starts the Task Manager.
  327.    """
  328.     pyautogui.hotkey('ctrl', 'shift', 'esc')
  329.  
  330. def start_on_screen_keyboard():
  331.     """
  332.    Starts the on-screen keyboard.
  333.    """
  334.     pyautogui.hotkey('ctrl', 'win', 'o')
  335.  
  336. def open_calculator():
  337.     """
  338.    Opens the Windows Calculator.
  339.    """
  340.     pyautogui.hotkey('win', 'r')
  341.     pyautogui.typewrite('calc')
  342.     pyautogui.press('enter')
  343.    
  344. def open_office_application(app):
  345.     """
  346.    Opens an Office application.
  347.  
  348.    Args:
  349.        app (str): The abbreviation of the Office application to open.
  350.            'w' for Word
  351.            'p' for PowerPoint
  352.            'x' for Excel
  353.            'o' for Outlook
  354.            't' for Teams
  355.            'd' for OneDrive
  356.            'n' for OneNote
  357.            'l' for LinkedIn
  358.            'y' for Yammer
  359.    """
  360.     pyautogui.hotkey('ctrl', 'shift', 'alt', 'win', app)
  361.    
  362. def load_hotkeys():
  363.     """
  364.    Load the hotkey configuration from the 'hotkeys.json' file.
  365.  
  366.    Returns:
  367.        dict: A dictionary containing the loaded hotkey configuration.
  368.    """
  369.     try:
  370.         with open("hotkeys.json", "r") as file:
  371.             hotkeys = json.load(file)
  372.     except FileNotFoundError:
  373.         hotkeys = {"known": PREDEFINED_HOTKEYS, "custom": {}}
  374.     return hotkeys
  375.  
  376. def save_hotkeys(hotkeys):
  377.     """
  378.    Save the hotkey configuration to the 'hotkeys.json' file.
  379.  
  380.    Args:
  381.        hotkeys (dict): A dictionary containing the hotkey configuration to be saved.
  382.    """
  383.     with open("hotkeys.json", "w") as file:
  384.         json.dump(hotkeys, file, indent=4)
  385.  
  386. def get_hotkey_input():
  387.     """
  388.    Get input for a custom hotkey sequence from the user.
  389.  
  390.    Returns:
  391.        list: A list representing the custom hotkey sequence.
  392.    """
  393.     print("Press your custom hotkey sequence. Press 'Esc' to finish input.")
  394.     hotkey = []
  395.     modifiers = set()  # Track pressed modifier keys
  396.     while True:
  397.         key = keyboard.read_event(suppress=True)
  398.         if key.event_type == "down":
  399.             if key.name == "esc":
  400.                 break
  401.             elif key.name in ["shift", "ctrl", "alt", "win"]:
  402.                 modifiers.add(key.name)
  403.             else:
  404.                 hotkey.append("+".join(modifiers))
  405.                 hotkey.append(key.name)
  406.                 modifiers.clear()
  407.                 print("Current input:", "+".join(hotkey))
  408.     return hotkey
  409.  
  410. def create_custom_hotkey():
  411.     """
  412.    Create a custom hotkey and save it to the hotkey configuration.
  413.    """
  414.     hotkeys = load_hotkeys()
  415.     hotkey = get_hotkey_input()
  416.     hotkey_str = "+".join(hotkey)
  417.     print("Your input:", hotkey_str)
  418.     if hotkey_str in hotkeys["known"]:
  419.         print(f"The hotkey '{hotkey_str}' already exists for {hotkeys['known'][hotkey_str]}.")
  420.         print("Do you want to overwrite it or go back? (1 to Overwrite, 0 to Go Back)")
  421.         choice = input().strip()
  422.         if choice == '0':
  423.             return
  424.     elif hotkey_str in hotkeys["custom"]:
  425.         print(f"The hotkey '{hotkey_str}' already exists for {hotkeys['custom'][hotkey_str]}.")
  426.         print("Do you want to overwrite it or go back? (1 to Overwrite, 0 to Go Back)")
  427.         choice = input().strip()
  428.         if choice == '0':
  429.             return
  430.     select_program()  # Open file explorer
  431.     program_path = input("Enter the program path or select the program file: ").strip()
  432.     hotkeys["custom"][hotkey_str] = program_path
  433.     save_hotkeys(hotkeys)
  434.  
  435. # Dictionary mapping shortcut numbers to functions
  436. shortcut_groups = {
  437.     "General Shortcuts": {
  438.         "1": open_start_menu,
  439.         "2": open_secret_start_menu,
  440.         "3": cycle_through_taskbar,
  441.         "4": go_to_nth_application,
  442.         "5": show_all_running_applications,
  443.         "6": show_hide_desktop,
  444.         "7": minimize_all_windows,
  445.         "8": temporary_show_desktop,
  446.         "9": magnify_screen_content,
  447.         "10": maximize_window,
  448.         "11": maximize_window_vertically,
  449.         "12": move_window_to_left_monitor,
  450.         "13": move_window_to_right_monitor,
  451.         "14": take_rectangular_screenshot,
  452.         "15": take_full_screenshot,
  453.         "16": open_calculator
  454.     },
  455.     "Virtual Desktop Shortcuts": {
  456.         "17": create_new_virtual_desktop,
  457.         "18": lambda: move_between_virtual_desktops("left"),
  458.         "19": lambda: move_between_virtual_desktops("right"),
  459.         "20": close_current_virtual_desktop
  460.     },
  461.     "System Shortcuts": {
  462.         "21": open_action_center,
  463.         "22": open_search,
  464.         "23": open_new_edge_tab,
  465.         "24": open_windows_settings,
  466.         "25": connect_sidebar,
  467.         "26": use_voice_typing,
  468.         "27": lock_computer,
  469.         "28": lock_screen_orientation
  470.     },
  471.     "Accessibility Shortcuts": {
  472.         "29": open_presentation_sidebar,
  473.         "30": open_ease_of_access_center,
  474.         "31": select_from_clipboard_history,
  475.         "32": set_focus_to_notification_area,
  476.         "33": open_emoji_panel,
  477.         "34": start_stop_narrator,
  478.         "35": quick_language_list,
  479.         "36": open_system_control_panel,
  480.         "37": start_task_manager,
  481.         "38": start_on_screen_keyboard
  482.     },
  483.     "Office Application Shortcuts": {
  484.         "39": lambda: open_office_application("w"),  # Word
  485.         "40": lambda: open_office_application("p"),  # PowerPoint
  486.         "41": lambda: open_office_application("x"),  # Excel
  487.         "42": lambda: open_office_application("o"),  # Outlook
  488.         "43": lambda: open_office_application("t"),  # Teams
  489.         "44": lambda: open_office_application("d"),  # OneDrive
  490.         "45": lambda: open_office_application("n"),  # OneNote
  491.         "46": lambda: open_office_application("l"),  # LinkedIn
  492.         "47": lambda: open_office_application("y")   # Yammer
  493.     },
  494.     "Create Custom Hotkey": {  # "Create Custom Hotkey" Group
  495.         "48": create_custom_hotkey
  496.     }
  497. }
  498.  
  499. # Descriptive names for office application functions
  500. descriptive_names = {
  501.     "17": "Move Left (Virtual Desktop)",    # Moves to the virtual desktop to the Left
  502.     "18": "Move Right (Virtual Desktop)",   # Moves to the virtual desktop to the Right
  503.     "38": "Open Word",
  504.     "39": "Open PowerPoint",
  505.     "40": "Open Excel",
  506.     "41": "Open Outlook",
  507.     "42": "Open Teams",
  508.     "43": "Open OneDrive",
  509.     "44": "Open OneNote",
  510.     "45": "Open LinkedIn",
  511.     "46": "Open Yammer"
  512. }
  513.  
  514. # Main function to execute shortcuts
  515. def main():
  516.     while True:
  517.         print("\nHotkey Main Menu:\n")
  518.         for index, group in enumerate(shortcut_groups.keys(), start=1):
  519.             print(f"{index:2}: {group}")
  520.         print(" 0: Exit")
  521.  
  522.         choice = input("\nEnter the number of the group you want to explore: ")
  523.         if choice == '0':
  524.             print("\nExiting Program...\tGoodBye!\n")  # Added exit message
  525.             break
  526.         elif choice.isdigit() and int(choice) in range(1, len(shortcut_groups) + 1):
  527.             group_index = int(choice) - 1
  528.             selected_group = list(shortcut_groups.keys())[group_index]
  529.             selected_shortcuts = shortcut_groups[selected_group]
  530.  
  531.             print(f"\n{selected_group} Options:\n")
  532.             for index, (key, value) in enumerate(selected_shortcuts.items(), start=1):
  533.                 if key in descriptive_names:  # Check if the key has a descriptive name (Not Lambda)
  534.                     name = descriptive_names[key]
  535.                 else:
  536.                     if callable(value):  # Check if it's a function or lambda
  537.                         if hasattr(value, '__name__'):  # For regular functions
  538.                             name = value.__name__.replace('_', ' ')
  539.                         else:  # For lambda functions
  540.                             name = "Custom Function"
  541.                     else:
  542.                         name = value.__class__.__name__  # Get class name for non-function values
  543.                 print(f"{index:2}: {name}")
  544.  
  545.             while True:
  546.                 sub_choice = input("\nEnter the number of the shortcut you want to execute (0 to go back): ")
  547.                 if sub_choice == '0':
  548.                     break
  549.                 elif sub_choice.isdigit() and int(sub_choice) in range(1, len(selected_shortcuts) + 1):
  550.                     selected_index = int(sub_choice) - 1
  551.                     selected_key = list(selected_shortcuts.keys())[selected_index]
  552.                     selected_shortcut = selected_shortcuts[selected_key]
  553.                     if callable(selected_shortcut):
  554.                         try:
  555.                             selected_shortcut()
  556.                         except Exception as e:
  557.                             print(f"An error occurred: {e}")
  558.                     else:
  559.                         print("Invalid choice. Please enter a valid number")
  560.                 else:
  561.                     print("Invalid choice. Please enter a valid number")
  562.         else:
  563.             print("Invalid choice. Please enter a valid number")
  564.  
  565. if __name__ == "__main__":
  566.     main()
  567.     create_custom_hotkey()
  568.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement