Skip to content

Instantly share code, notes, and snippets.

@mahmoudimus
Forked from apfelchips/macOS-shortcuts.ahk
Created January 10, 2023 00:24
Show Gist options
  • Save mahmoudimus/97c1e926f6cbbc8d84ed6c9dca274ed2 to your computer and use it in GitHub Desktop.
Save mahmoudimus/97c1e926f6cbbc8d84ed6c9dca274ed2 to your computer and use it in GitHub Desktop.
First remap modifier keys with sharpkeys; AHK script has to run as Administrator to work on System Windows / Apps running as Administrator; see Watchdog ScheduledTask below, when you do this make sure to remove the inherited file permissions from C:/tools and only allow administrators write access.
#NoEnv ; Recommended for performance and compatibility with future AutoHotkey releases.
;#NoTrayIcon
Menu, Tray, Icon, accessibilitycpl.dll, 6 ; Keyboard Icon
;#Persistent https://www.autohotkey.com/docs/commands/_Persistent.htm
SendMode Input ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir% ; Ensures a consistent starting directory.
#SingleInstance force
; Debugging
#Warn All, OutputDebug ; Show Warnings on DebugView
#Warn UseUnsetLocal, Off ; Can't use default Parameters without warning
; src: https://gist.github.com/apfelchips/e30321f33abc1eb1a481e83b1e79d5c5/
; doc:
; https://www.ahkgen.com/
; https://autohotkey.com/docs/Hotkeys.htm
; https://autohotkey.com/docs/KeyList.htm
; https://www.autohotkey.com/docs/commands/Send.htm
; Ref https://github.com/rbreaves/kinto/blob/master/windows/kinto.ahk
; Ref https://autohotkey.com/board/topic/60675-osx-style-command-keys-in-windows/
; Ref https://gist.github.com/trevoreyre/8df3a186bb18df4b17d5417a5d1143ad
; Ref https://github.com/Drugoy/Autohotkey-scripts-.ahk
; ^ = Control
; ! = Alt
; + = Shift
; # = Windows
; * = Wildcard / ignore Modifiers
; $ = no Recursion
; ~ = no Key Masking
; sc063 = Thinkpad FN
; sharpkeys: https://github.com/randyrants/sharpkeys/releases/
; online .reg remap generator: https://n8ta.com/projects/windows_key_remapper.html
; LWin --> LALT
; LAlt --> RControl
; optional (right side)
; RAlt --> RControl
; RWin --> RAlt
; AppsKey --> RWin
; optional (needed for AppleKeyboardLayoutMode)
; LControl --> 0x005C
; Remap keys back
sc005C::LControl
; define application groups
;GroupAdd AltTabWindow, ahk_class MultitaskingViewFrame ; Windows 10
;GroupAdd AltTabWindow, ahk_class TaskSwitcherWnd ; Windows Vista, 7, 8.1
;GroupAdd AltTabWindow, ahk_class #32771 ; Older, or with classic alt-tab enabled
; reset modifiers / CapsLock on Startup
Send {Shift up}
Send {Control up}
Send {LControl up}
Send {RControl up}
Send {Alt up}
Send {LWin up}
Send {RWin up}
Send {CapsLock up}
;SetStoreCapsLockMode, Off
;SetCapsLockState, AlwaysOff
+CapsLock::CapsLock
CapsLock::Ctrl
AutoElevate = true
; src: https://autohotkey.com/board/topic/46526-run-as-administrator-xpvista7-a-isadmin-params-lib/?p=289601
param := ""
params := ""
Loop, %0% ; For each parameter:
{
param := %A_Index% ; Fetch the contents of the variable whose name is contained in A_Index.
params .= A_Space . param
}
ShellExecute := A_IsUnicode ? "shell32\ShellExecute":"shell32\ShellExecuteA"
if not A_IsAdmin and %AutoElevate%
{
If A_IsCompiled
DllCall(ShellExecute, uint, 0, str, "RunAs", str, A_ScriptFullPath, str, params , str, A_WorkingDir, int, 1)
Else
DllCall(ShellExecute, uint, 0, str, "RunAs", str, A_AhkPath, str, """" . A_ScriptFullPath . """" . A_Space . params, str, A_WorkingDir, int, 1)
ExitApp
}
Log(msg){
OutputDebug, [AHK] %Msg%
}
; #SetTitleMatchMode RegEx breaks too much / has undefined behaviour
WinActiveProcessRegEx(regexNeedle, comfort:=true){
WinGet, tmp, ProcessName, A
if (comfort){
regexNeedle := "i)^" . regexNeedle . "$"
}
return RegExMatch(tmp, regexNeedle)
}
WinActiveClassRegEx(regexNeedle, comfort:=true){
WinGetClass, tmp, A
if (comfort){
regexNeedle := "i)^" . regexNeedle . "$"
}
return RegExMatch(tmp, regexNeedle)
}
WinActiveTitleRegEx(regexNeedle, comfort := true){
WinGetTitle, tmp, A
if (comfort){
regexNeedle := "i)" . regexNeedle
}
return RegExMatch(tmp, regexNeedle)
}
CountWindows(){
WinGet windows, List, , , ,
wCount := 0
wTitleOut := ""
Loop %windows%
{
id := windows%A_Index%
WinGetTitle wTitle, ahk_id %id%
;wTitleOut .= wTitle . "`n"
if (wTitle != "") {
wCount += 1
}
}
;MsgBox, %wCount%
return %wCount%
}
WaitForWindowChange(){
If (WinActiveClassRegEx("Windows\.UI\.Core\.CoreWindow")){
return
}
WinWaitNotActive, A
return
}
;reset all modifiers on escape
*~Esc::
Send {Control up}
Send {LControl up}
Send {RControl up}
Send {Shift up}
Send {Alt up}
Send {LWin up}
Send {RWin up}
Send {CapsLock up}
SetCapsLockState, Off
return
/**
* Disable Alt key acceleration.
* These next two lines are very important. You have to change the "menu mask
* key" away from being Control, to something that won't result in cross-talk.
* https://autohotkey.com/boards/viewtopic.php?f=76&t=57683
*/
; Send{Alt up}{sc0EA up}{sc0E9 up} when using alt
#MenuMaskKey vk07 ; vk07 is unassigned
;#UseHook On ; https://www.autohotkey.com/docs/commands/_UseHook.htm
~LAlt::
Sendinput {Blind}{sc0E9}
KeyWait, LAlt ; this wasit for the key to be RELEASED. So that it doesn't keep spamming SC0E9 (as seen from an AHK window Key history and script info... window.)
Sendinput {Blind}{sc0EA}
return
~RAlt::
Sendinput {Blind}{sc0E9}
KeyWait, RAlt ; so that it doesn't keep spamming SC0E9
Sendinput {Blind}{sc0EA}
return
;#UseHook Off
#If ( WinActiveProcessRegEx("ConEmu(64)?\.exe") )
~LAlt::
Sendinput {Blind}
return
~RAlt::
Sendinput {Blind}
return
#If
; rctrl+Tab --> Expose
+F11::
>^Tab::
>^+Tab::
;$!<Tab::
;$!<+Tab::
Send #{Tab}
Send {Control up} ; sometimes get stuck here
; Send {Alt up}{sc0EA up}{sc0E9 up}{LWin down}{Tab}{LWin up}
return
; BROKEN: somethimes hangs
; Command-Tab --> Switch windows
; Ref: https://autohotkey.com/board/topic/148298-ctrl-tab-ctrl-shift-tab-for-alttabshiftalttab-task-switching-windows-10/
; https://www.autohotkey.com/docs/Hotkeys.htm#AltTabRemarks
;#If ( CountWindows() > 0 )
; >^Tab::
; Send {Alt down}{Tab}
; return
; >^+Tab::
; Send {Alt down}{Shift down}{Tab}{Shift up}
; return
;#If
;#If ( WinExist("ahk_class MultitaskingViewFrame") )
; ~sc0EA up::
; ~sc0E9 up::
; ~*Alt up::
; ~*Esc::
; Control up:: ; RControl up or LControl up don't get detected reliably!!!
; Send {Alt up}
; return
;#If
; disable StartMenu on Command+Escape
$>^Escape::
SendInput +{Escape}
return
; StartMenu aka Spotlight light
>^Space::
Send {blind}^<{Esc}
return
; Command+Shift+V - Pure / PlainText Clipboard
$>^+v::
wholeclipboard:=ClipboardAll
Clipboard=%Clipboard%
Sleep, 100 ; wait for clipboard to be cleansed
Send ^{v}
Sleep, 100 ; wait before restoring original clipboard content
Clipboard:=wholeclipboard
return
; Command-M / Command-H - Minimize active window
$>^m::
$>^h::
WinMinimize, A
return
; Command-R - Reload
$>^r::
Send {F5}
return
$>^q::
$!f4::
if ( WinActiveProcessRegEx("notes2\.exe") or ( WinActiveProcessRegEx("Outlook\.exe") and WinActiveTitleRegEx("- Outlook$") ) or WinActiveProcessRegEx("PSRClient\.exe") ){
WinMinimize, A
} else if (WinActiveProcessRegEx("explorer\.exe") and ( WinActiveClassRegEx("Progman") or WinActiveClassRegEx("WorkerW") or WinActiveClassRegEx("Shell_TrayWnd") )) {
; do nothing to prevent opening the shutdown dialog
} else {
Send {LAlt down}{F4}{LAlt up}
;WinClose, A
}
return
; "force close"
$>^!<q::
WinKill, A
return
$#+w:: ; Logitech Options Gesture Mapping
$>^w::
if ( WinActiveProcessRegEx("KeePassXC\.exe")
or WinActiveProcessRegEx("SumatraPDF\.exe")
or WinActiveProcessRegEx("mdview\.exe")
or WinActiveProcessRegEx("AutoHotkey\.exe")
or WinActiveClassRegEx("Photo_Lightweight_Viewer")
or WinActiveClassRegEx("TaskManagerWindow")
or (WinActiveProcessRegEx("Outlook\.exe") and not ( WinActiveTitleRegEx("- Outlook$") ))
or (WinActiveProcessRegEx("ApplicationFrameHost\.exe") and not WinActiveTitleRegEx("- Remote Desktop$")) ; UWP apps
or (WinActiveProcessRegEx("explorer\.exe") and ( not ( WinActiveClassRegEx("Progman") or WinActiveClassRegEx("WorkerW") or WinActiveClassRegEx("Shell_TrayWnd") ))) )
{
WinClose, A
} else if ( WinActiveProcessRegEx("WindowsTerminal\.exe") ){
Send +^{w}
} else if ( WinActiveProcessRegEx("PSRClient\.exe") ){
Send {Esc}
} else if ( WinActiveTitleRegEx("- Outlook$") or WinActiveProcessRegEx("Teams\.exe")){
WinMinimize, A
} else if ( WinActiveProcessRegEx("ConEmu(64)?\.exe")){ ; Programs that can differentiate between LControl <=> RControl
Send {RControl down}{w}{RControl up}
} else {
Send ^{w}
}
return
; Sublime Notes Shortcut
;#If ( WinActiveProcessRegEx("sublime_text\.exe") and WinActiveTitleRegEx("\(notes\).-.Sublime.Text$"))
; !Space::
; Send ^{p}
; return
;#If
;!Space::
; ;; SetTitleMatchMode 3
; ;; DetectHiddenWindows, On
; ;; WinGet, obsidian_window_id, IDLast, ahk_exe Obsidian.exe
; ;; SetTitleMatchMode 1
;
; EnvGet, ProgFiles, ProgramFiles
; EnvGet, UserProfile, UserProfile
; RunWait %ProgramFiles%\Sublime Text\subl.exe %UserProfile%\Nextcloud\notes\notes.sublime-project,
; if ErrorLevel {
; Run notepad.exe ; fallback software tip: https://www.binaryfortress.com/NotepadReplacer/Download/
; }
; ;; DetectHiddenWindows, Off
;return
#If (WinActiveProcessRegEx("Outlook\.exe") and ( WinActiveTitleRegEx("- Outlook$") ))
Ins::
Send {LControl down}{q}{LControl up}
return
#If
#If (WinActiveProcessRegEx("notes2\.exe") )
^<TAB::
^<+TAB::
Send {blind}{F8}
return
#If
;; Windows Terminal RCtrl Shim | https://aka.ms/terminal-keybindings
#If ( WinActiveProcessRegEx("WindowsTerminal\.exe"))
>^c::Send {blind}{Shift down}{c}{Shift up}
>^v::Send {blind}{Shift down}{v}{Shift up}
>^n::Send {blind}{Shift down}{n}{Shift up}
>^t::Send {blind}{Shift down}{t}{Shift up}
>^f::Send {blind}{Shift down}{f}{Shift up}
>^a::Send {blind}{Shift down}{a}{Shift up}
#If
;; macOS text navigation
; Command-Shift-arrow navigation + highlight
;;>^+Left::Send {Shift down}{Home}{Shift up}
;;>^+Right::Send {Shift down}{End}{Shift down}
;;>^+Up::Send {Control down}{Shift down}{Home}{Shift up}{Control up}
;;>^+Down::Send {Control down}{Shift down}{End}{Shift up}{Control up}
;; Option-arrow navigation
;;!<Left::Send {Control down}{Left}{Control up}
;;!<Right::Send {Control down}{Right}{Control up}
;; Option-Shift-arrow navigation + highlight
;;!<+Left::Send {Control down}{Shift down}{Left}{Shift up}{Control up}
;;!<+Right::Send {Control down}{Shift down}{Right}{Shift up}{Control up}
; Command-D - Delete forward
;;>^d::Send {Delete}
;; Command-Delete - Delete line
;;>^Backspace::Send {Shift down}{Home}{Shift up}{Delete}
;; Command-Shift-Delete - Delete line forward
;;>^+Backspace::Send {Shift down}{End}{Shift up}{Delete}
;; Option-Delete - Delete word
;;!Backspace::Send {Control down}{Backspace}{Control up}
;; Option-Shift-Delete - Delete word forward
;;!+Backspace::Send {Control down}{Delete}{Control up}
;; Screenshots
; https://docs.microsoft.com/en-us/windows/uwp/launch-resume/launch-screen-snipping
$+>^3::
$+>^4::
Run, explorer.exe ms-screenclip:
;Run, C:\WINDOWS\system32\SnippingTool.exe /clip ; legacy Snipping Tool
return
;; Finder Emulation
#If ( WinActiveProcessRegEx("explorer\.exe") and WinActiveClassRegEx("CabinetWClass") )
>^Left::
SendEvent {RControl up}
SendEvent !{Left}
return
>^Right::
SendEvent {RControl up}
SendEvent !{Right}
return
>^Up::
SendEvent {RControl up}
SendEvent !{Up}
return
>^Down::
SendEvent {RControl up}
SendEvent !{Down}
return
#If
;; Affinity Suite RControl weirdness fix
#If ( WinActiveProcessRegEx("photo\.exe") ) or ( WinActiveProcessRegEx("designer\.exe") ) or ( WinActiveProcessRegEx("publisher\.exe") )
>^d::
Send ^{d}
return
#If
#If ( WinActiveProcessRegEx("explorer\.exe") )
$+Enter::
SendEvent {F2} ; rename action
return
$>^o::
Send {Control up}
SendEvent {Control up}
SendEvent {Enter}
return
$!>^i::
$>^i::
SendEvent !{Enter}
return
$^+.::
RegRead, HiddenFiles_Status, HKEY_CURRENT_USER, Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced, Hidden
if (HiddenFiles_Status = 2){
RegWrite, REG_DWORD, HKEY_CURRENT_USER, Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced, Hidden, 1
Send {F5}
} else {
RegWrite, REG_DWORD, HKEY_CURRENT_USER, Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced, Hidden, 2
Send {F5}
}
return
$>^k:: ; connect to server
$>^+g:: ; goto file
if ( WinActiveClassRegEx("CabinetWClass") ){
SendEvent {F4}
}
else if ( WinActiveClassRegEx("Progman") ){
Run, explore %A_MyDocuments%\..\
Sleep, 200
SendEvent {F4}
}
return
$>^+Backspace::
$>^+Delete::
MsgBox, 1, ,"Empty Recycle Bin?"
IfMsgBox Ok
FileRecycleEmpty
return
#If
' Usage:
' wscript.exe //E:vbscript HiddentPowershell.vbs -ExecutionPolicy ByPass -File "C:\Program Files\Get-HelloWorld.ps1"
'
' Will run Powershell in a hidden console, like this:
' powershell.exe -ExecutionPolicy ByPass -File "C:\Program Files\Get-HelloWorld.ps1"
'
' More Info: https://github.com/UNT-CAS/HiddenPowershell
Set oShell = CreateObject("Wscript.Shell")
Const LOG_EVENT_SUCCESS = 0
Const LOG_EVENT_ERROR = 1
Const LOG_EVENT_INFORMATION = 4
Dim iExitStatus : iExitStatus = LOG_EVENT_SUCCESS
Dim sArgs : sArgs = "powershell.exe"
Dim sMessage : sMessage = ""
For Each sArg in Wscript.Arguments
If InStr(sArg, " ") > 0 Then
' If there's a space in the argument, wrap it in quotes.
sArgs = sArgs & " """ & sArg & """"
Else
sArgs = sArgs & " " & sArg
End If
Next
sMessage = "HiddenPowershell Running: " _
& vbCrLf & vbTab & Wscript.ScriptFullName _
& vbCrLf & vbTab & sArgs
oShell.LogEvent LOG_EVENT_INFORMATION, sMessage
iReturn = oShell.Run(sArgs, 0, True)
If iReturn <> 0 Then
iExitStatus = LOG_EVENT_ERROR
End If
sMessage = "HiddenPowershell Exited: " _
& vbCrLf & vbTab & Wscript.ScriptFullName _
& vbCrLf & vbTab & sArgs _
& vbCrLf & vbTab & "Exit Code: " & iReturn
oShell.LogEvent iExitStatus, sMessage
Wscript.Quit iReturn
while ($true) {
$WatchedProcesses = Get-CimInstance -ClassName Win32_Process -Filter "name = 'AutoHotkey.exe'"
$WatchedCli = Write-Output $WatchedProcesses | Select CommandLine | Select-String -Pattern 'macOS-shortcuts.ahk'
if ( $WatchedCli.Count -eq 0 ){
Start-Process -FilePath "${env:ProgramFiles}\AutoHotkey\Autohotkey.exe" -ArgumentList "${env:SystemDrive}\tools\macOS-shortcuts.ahk" -Verb RunAs
Write-Host "starting watched process"
}
#Write-Host "nothing to do, waiting..."
Start-Sleep -s 35
}
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<RegistrationInfo>
<Date>2021-03-18T16:51:09.0308012</Date>
<Author>apfelchips</Author>
<URI>\macOS-shortcuts-watchdog</URI>
</RegistrationInfo>
<Triggers>
<LogonTrigger>
<Enabled>true</Enabled>
<UserId>.\user</UserId>
<Delay>PT13S</Delay>
</LogonTrigger>
</Triggers>
<Principals>
<Principal id="Author">
<UserId>xxxxxxxxxxxxxxxxx</UserId>
<LogonType>InteractiveToken</LogonType>
<RunLevel>HighestAvailable</RunLevel>
</Principal>
</Principals>
<Settings>
<MultipleInstancesPolicy>StopExisting</MultipleInstancesPolicy>
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
<AllowHardTerminate>true</AllowHardTerminate>
<StartWhenAvailable>false</StartWhenAvailable>
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
<IdleSettings>
<StopOnIdleEnd>true</StopOnIdleEnd>
<RestartOnIdle>false</RestartOnIdle>
</IdleSettings>
<AllowStartOnDemand>true</AllowStartOnDemand>
<Enabled>true</Enabled>
<Hidden>true</Hidden>
<RunOnlyIfIdle>false</RunOnlyIfIdle>
<WakeToRun>false</WakeToRun>
<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
<Priority>7</Priority>
</Settings>
<Actions Context="Author">
<Exec>
<Command>C:\Windows\System32\wscript.exe</Command>
<Arguments>"C:\tools\HiddenPowershell.vbs" -ExecutionPolicy ByPass -noProfile -File "C:\tools\macOS-shortcuts-watchdog.ps1"</Arguments>
</Exec>
</Actions>
</Task>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment