0

I have wrote the following program. I made its setup. It installed successfully. Now, I want my program to start at startup without manually copying its shortcut to startup folder i.e C:\Users\User\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup.

I would like my program to run automatically at startup like many commercial programs (like utorrent, Internet Downloader Manager, etc) do. How can I do that?

Ghantey
  • 626
  • 2
  • 11
  • 25
  • wait, is your question about the code, or about automating tasks in Windows? – Paul H Jun 28 '18 at 15:59
  • i think he's asking what python code to add that will run this script on startup. – ltd9938 Jun 28 '18 at 16:00
  • There is a startup folder in windows. put the links to programs simply there and it will start on startup – Superluminal Jun 28 '18 at 16:01
  • @sgerodes "I want my program start at startup without manually copying its shortcut to startup folder" – ltd9938 Jun 28 '18 at 16:01
  • why not? That is what it is created for. I my thought it is faster to copy some shortcuts than to write a program. There is a Developer wisdom that sounds something like "do not do something that already is done" – Superluminal Jun 28 '18 at 16:23

1 Answers1

2

To avoid adding it to the startup folder, you can place your file elsewhere and create a Registry Key in the current user's startup Registry folder. To do so—utilize the winreg module. It's well documented and fun to use!

winreg.CreateKeyEx(key, sub_key, reserved=0, access=KEY_WRITE)
winreg.SetValueEx(key, value_name, reserved, type, value)
winreg.Close()

Basic Usage

import winreg

def create_key(name: str="default", path: ""=str)->bool:
    # initialize key (create) or open
    reg_key = winreg.CreateKeyEx(winreg.HKEY_CURRENT_USER, # path current user
                                 r'Software\Microsoft\Windows\CurrentVersion\Run', # sub path startup
                                 0, # reserved (must be zero, default is 0)
                                 winreg.KEY_WRITE) # set permission to write

    # CreateKey returns a handle
    # if null it failed
    if not reg_key:
        return False

    # set the value of created key
    winreg.SetValueEx(reg_key, # key
        name,                  # value name
        0,                     # reserved (must be zero, default is 0)
        winreg.REG_SZ,     # REG_SZ - null-terminated string (for file path)
        path) # set file path

    # close key (think of it as opening a file)
    reg_key.Close()
    return True

if create_key("startup_batch", r"C:\Users\admin\Desktop\test.bat"):
    print("Added startup key.")
else:
    print("Failed to add startup key.")

Coded with version 3.6.4.

Community
  • 1
  • 1
Noah M.
  • 310
  • 1
  • 8