Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a hotkey to open a file in windows

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.

like image 671
Abhay Salvi Avatar asked Oct 22 '25 10:10

Abhay Salvi


1 Answers

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.

like image 148
mklement0 Avatar answered Oct 24 '25 23:10

mklement0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!