Home > Enterprise >  How to show exe file in right click context menu in Python for desktop software / app?
How to show exe file in right click context menu in Python for desktop software / app?

Time:11-21

I wrote a python script and then convert it into executable file. In below image you can see my exe file. my exe file.

Now, I want to show my exe file in context menu after right click only on the folder, I also want to take folder name as an argument, than user click the exe file which I want to show in a right click context menu.

In this image you can easily understand, what i want.

CodePudding user response:

This is what I used for a simple app I wrote, it has stupid logic to check if it's run with or without arguments, and tries to add an entry to the context menu when it's run without arguments (eg. directly, not from context menu)

Just for simple explanation:

  1. Running the EXE directly will create a .reg file and run said registry file. This will add the menu entry to the context menu. It uses the path of the EXE to tell windows where the EXE can be found.
  2. After this, when right-clicking a file/directory/whatever, it will show the menu entry and if you click on that, it won't meet the contitions for the if statement, so it will continue with the rest of the script.

I'm not sure how this handles different Windows versions, as it was made specifically for Windows 11 and I added zero error checking.

import sys
import os


context_menu_text_string = "This is the text shown in the context menu"

if len(sys.argv) != 2:
    repl = sys.argv[0].replace("\\", "\\\\")
    with open("registryfile.reg", "w") as outfile:
        outfile.write(
            rf"""Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Directory\Background\shell\{context_menu_text_string}\command]
@="{repl} \"%1\""
"""
        )
    os.startfile("registryfile.reg")
    input("Press enter to continue, after finishing the registry import...")
    os.remove("registryfile.reg")
    sys.exit(0)


full_file_path = sys.argv[1]

# your logic here, full_file_path contains the path to 
# the file/directory which was right-clicked
  • Related