Home > Software design >  How to create a hotkey to open a file in windows
How to create a hotkey to open a file in windows

Time:10-14

I am creating an application and I want that when the user opens my app, it should create a hotkey for itself like ctrl alt f so that the app automatically runs everytime the user presses those key combinations.

I know how to achieve this manually in windows by right-clicking the app and adding a key combination but I don't know how to achieve this programmatically as I don't want the user to do this by their own.

CodePudding user response:

You can programmatically create a shortcut file (*.lnk) that points to your application executable, which also allows defining a hotkey for invocation.

The following example creates MyApp.lnk on your Desktop, which launches Notepad, optionally via hotkey Ctrl Alt F; the hotkey takes effect instantly:

  • Caveat: Only shortcut files saved to select directories ensure that their hotkey definitions take effect persistently, i.e. continue to work after reboots. The (current user's) Desktop works - I'm unclear on what other directories work as well.
# Get the Desktop dir. path.
$desktopDir = [Environment]::GetFolderPath('Desktop') 

# Create the shortcut object, initially in-memory only.
$shc = 
  (New-Object -ComObject 'Wscript.Shell').CreateShortcut("$desktopDir\MyApp.lnk") 

# Set the target executable (name will do if in $env:PATH).
# If arguments must be passed, use the separate .Arguments property (single string)
$shc.TargetPath = 'notepad.exe' 

# Assign the hotkey.
$shc.Hotkey = 'Ctrl Alt F'

# Save to disk (using the initially specified path).
$shc.Save() 

See the documentation of the WshShortcut COM object, of which the above creates an instance.

  • Related