Pressing a key specific number of times to take different actions Topic is solved

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
arrondark
Posts: 29
Joined: 01 May 2024, 05:27

Pressing a key specific number of times to take different actions

17 May 2024, 13:10

I am trying to find different ways by which I can press a single button on my keyboard specific times to take different actions, like if I press 1 it should open the explorer, and on pressing the key twice it should open the calculator, and if I press thrice it should open my browser etc.
I tried but at the end I found a script from a YouTuber name Juho Lee
Here is the script:
Though I changed few things and tweak it sometime but it worked for me mostly

Code: Select all

NumpadDiv::
If (KeyPressCount > 0)
	{
		KeyPressCount +=1
	}
else
	{
		KeyPressCount :=1
	}
if (KeyPressCount >2)
	{
		Tooltip, % KeyPressCount
	}

SetTimer, oKeyPressMonitor, 300
return
oKeyPressMonitor:
If (KeyPressCount = 1)
	{
		SendInput, ^{PrintScreen}
	}
else if (KeyPressCount > 1)
	{
		SendInput, ^+/
	}
KeyPressCount := 0
SetTimer, oKeyPressMonitor, Off
Tooltip,
return
Now I am wondering is there any way better than this to implement the same function, like implementation without timer or may it only be activated on the same key not any other because in the above code if you pressed once with the assigned key and then changed it another key it would be still counted(key counted)(even though its a different key) if it is pressed under the set limit.
User avatar
CoffeeChaton
Posts: 36
Joined: 11 May 2024, 10:50

Re: Pressing a key specific number of times to take different actions

17 May 2024, 13:59

Code: Select all

global ClickCount
NumpadDiv:: fn_NumpadDiv_withClick() 

fn_NumpadDiv_withClick() {
    If (ClickCount > 0) {
        ClickCount += 1
    } else {
        ClickCount := 1
    }
    Tooltip, %ClickCount%
    SetTimer, oKeyPressMonitor, -1500
}

oKeyPressMonitor() {
    If (ClickCount = 1) {
        ; SendInput, ^{PrintScreen}
        MsgBox, % "t1"
    } else if (ClickCount > 1) {
        ; SendInput, ^+/
        MsgBox, % "t2"
    }

    ClickCount := 0
    SetTimer, oKeyPressMonitor, Off
    Tooltip
}
simplify and let SetTimer, oKeyPressMonitor, 300 to -1500,
change 300(0.3 sec loop) to -1500 (1.5 sec not loop),
I don't think infinite loop is normal, it seems a bit difficult to press 2 or even 3 times within 0.3sec at the same time.


if you want not SetTimer , you can use KeyWait. https://www.autohotkey.com/docs/v1/lib/KeyWait.htm
be activated on the same key not any other because in the above code if you pressed once with the assigned key and then changed it another key it would be still counted(key counted)(even though its a different key) if it is pressed under the set limit.
Can you provide the full script, I don't think the part I saw has this problem.
arrondark
Posts: 29
Joined: 01 May 2024, 05:27

Re: Pressing a key specific number of times to take different actions

18 May 2024, 01:53

Thank you for V0RT3X, I tried it and it worked but the issue now I am facing is that whenever I am calling a function for showing menu I am having multiple on the bottom(of menu).
Below is the code:

Code: Select all

#IF (mbtnstate=0)
;Hotkey to select area
Mbutton::
SCW_ScreenClip2Win(clip:=0) ; set to 1 to auto-copy to clipboard
WinActivate, ScreenClippingWindow ahk_class AutoHotkeyGUI
If (ClickCount > 0)
	{
		ClickCount +=1
	}
else
	{
		ClickCount :=1
	}
If (ClickCount > 1 AND ClickCount < 4)
    Tooltip, %ClickCount%
SetTimer, mbclickmonitor, 500
return
mbclickmonitor:
If (ClickCount = 2)
	{
		Send, {Media_Play_Pause}
	}
else if (ClickCount > 2)
	{
		MNFunctionmenu() ;from here i am calling the function
	}
ClickCount := 0
SetTimer, mbclickmonitor, Off
Tooltip,
return
#IF

#IF (whelscrlfn=1)
{
    WheelUp::Right
    WheelDown::Left
}
#IF

;============================================================================================================
;============================================================================================================
;Menu function and call
;InstantMenu is a function which can be called from any where or any if else statments
;current states of key always on top of script
;make a menu
;name of the menu is MNFunctions
MNFunctionmenu()
{
    Menu, MNFunctions, Add, Schreenshot State, Screenshot1orScreenshot2State 
    Menu, MNFunctions, Add, SpeedUpDown_UnRe State, SpeedUpDownorUndoRedo_State
    Menu, MNFunctions, Add, CopyCut/CopylinkCopyCut State, CopyCutorCopylinkCopyCutState
    Menu, MNFunctions, Add, Play Pause 4 All - PlayPause 4 Nox State, MediaPlay4AllorMediaPlay4NoxState
    Menu, MNFunctions, Add
    Menu, MNFunctions, Add
    Menu, MNFunctions, Add, Media Key 4 OneNote State, MediaKey4OneNoteorMediaKey4AllState
    Menu, MNFunctions, Add, Fn Key Enable/Disable, fnkeystateenabledisable
    Menu, MNFunctions, Add, Scroll Up/Down - Arrow State, wheelupdownarrow
    Menu, MNFunctions, Add, Mouse_Middle_Button Enable/Disable , mousembuttonenabledisable
    Menu, MNFunctions, Add
    Menu, MNFunctions, Add
    Menu, MNFunctions, Add, Lecture Recordings, lectruerecordingopen
    Menu, MNFunctions, Add, Explore E_D, exploreedopen
    Menu, MNFunctions, Add
    Menu, MNFunctions, Add
    Menu, MNFunctions, Add, OneNote, OneNoterunner
    Menu, MNFunctions, Add, Calculator, calculatorrunneropen
    Menu, MNFunctions, Add, Notepad, notepadrunneropen
    Menu, MNFunctions, Add
    Menu, MNFunctions, Add
    Menu, MNFunctions, Add
    Menu, MNFunctions, Add, Exit App, exiterapp
    Menu, MNFunctions, Show
}


Screenshot1orScreenshot2State: ;create non-spaced labels for menu items
{
	scrstate := !scrstate
	if (scrstate=0)
		{
			MsgBox, 262144, Screenshot Key Press,
			(
				Screenshot  - 2 press
				`nRepeat last - 1 press
			) 
		}
	else if (scrstate=1)
		{
			MsgBox, 262144, Screenshot Key Press,
			(
				Screenshot  - 1 press
				`nRepeat last - 2 press
			)
		} 	
}
Return

SpeedUpDownorUndoRedo_State:
{
	spustate := !spustate
	if (spustate=0)
		{
			MsgBox, 262144, Speed up/down,
			(
				^ - speed up
				`nv - speed down
			) 
		}
	else if (spustate=1)
		{
			MsgBox, 262144, undo/redo,
			(
				^ - redo
				`nv - undo
			) 
		} 
}
Return

CopyCutorCopylinkCopyCutState:
{
	cpcstate := !cpcstate
	if (cpcstate=0)
		{
			MsgBox, 262144, copy/cut,
			(
				copy - 1 press
				`ncut  - 1 press
			) 
		}
	else if (cpcstate=1)
		{
			MsgBox, 262144, copylink/copy/cut,
			(
				copylink(onenote) - 1 press
							 `ncopy - 2 press
							  `ncut - 3 press
			) 
		} 
}
Return

MediaPlay4AllorMediaPlay4NoxState:
{
	mdastate:=!mdastate
	SoundBeep, 300, 700
	if (mdastate = 1)
		{
			SplashTextOn,250,60,,Play/Pause for nox
			Sleep 400
			SplashTextOff
			if (fnstate = 0)
				{
					Menu, Tray, Icon, fndisableone_nox.ico
				}
			else if (fnstate = 1)
				{
					Menu, Tray, Icon, fnenableone_nox.ico
				}
		}
	else if (mdastate = 0)
		{
			SplashTextOn,250,60,,Play/Pause for all 
			Sleep 400
			SplashTextOff
			if (fnstate = 0)
				{
					Menu, Tray, Icon, fndisableone_all.ico
				}
			else if (fnstate = 1)
				{
					Menu, Tray, Icon, fnenableone_all.ico
				}
		}
}
Return

MediaKey4OneNoteorMediaKey4AllState:
{
	mdkystate := !mdkystate
	if (mdkystate=0)
		{
			MsgBox, 262144, Media_Play_Pause,
			(
				Play/Pause - Play/Pause
			) 
		}
	else if (mdkystate=1)
		{
			MsgBox, 262144, Media_Play_Pause,
			(
				Play/Pause - ctrl + shift + 6
			) 
		} 
}
Return

fnkeystateenabledisable:
{
	fnstate:=!fnstate
	SoundBeep, 900, 500
	if (fnstate = 1)
		{
			if (mdastate = 0)
				{
					Menu, Tray, Icon, fnenableone_all.ico
				}
			else if (mdastate = 1)
				{
					Menu, Tray, Icon, fnenableone_nox.ico
				}
		}
	else if (fnstate = 0)
		{
			if (mdastate = 0)
				{
					Menu, Tray, Icon, fndisableone_all.ico
				}
			else if (mdastate = 1)
				{
					Menu, Tray, Icon, fndisableone_nox.ico
				}
	}
}
Return

wheelupdownarrow:
{
    whelscrlfn:=!whelscrlfn
    if (whelscrlfn=0)
        {
            MsgBox, 262144, Scroll Up/Down,
            (
                Scroll Up   - Scroll Up
                `nScroll Down - Scroll Down
            )
        }
    else if (whelscrlfn=1)
        {
            MsgBox, 262144, Scroll Up/Down,
            (
                Scroll Up   - Arrow Right
                `nScroll Down - Arrow Left
            )
        } 
}
Return

mousembuttonenabledisable:
{
    mbuttonstate:=!mbuttonstate
    if (mbuttonstate=0)
        {
            SplashTextOn,350,100,,Scroll Button Disable
            Sleep 400
            SplashTextOff
        }
    else if (whelscrlfn=1)
        {
            SplashTextOn,350,100,,Scroll Button Enable
            Sleep 400
            SplashTextOff
        } 
}
Return

lectruerecordingopen:
run, C:\Users\amana\Music\Lecture Recordings
Return

exploreedopen:
run, C:\DaTa\E_D
Return

OneNoterunner:
run, ONENOTE
Return

calculatorrunneropen:
run, Calc
Return

notepadrunneropen:
run, Notepad
Return

exiterapp:
{
    SplashTextOn,150,40,,Exit Script
    Sleep 400
    SplashTextOff
    ExitApp
}
Return

After accessing the menu for the very first time I don't have any issueImage but when I again press thrice to get the menu I have multiple lines in the bottom of it and the lines keep on increasing.Image
image.png
image.png (16.77 KiB) Viewed 287 times
Attachments
image.png
image.png (19.42 KiB) Viewed 287 times
arrondark
Posts: 29
Joined: 01 May 2024, 05:27

Re: Pressing a key specific number of times to take different actions

18 May 2024, 06:27

Here is the whole code CoffeeChaton:

Code: Select all

;https://www.autohotkey.com/docs/scripts/index.htm#TooltipMouseMenu
;hotkey changed from long press MButton to RButton

; ToolTip Mouse Menu (requires XP/2k/NT) -- by Rajat
; https://www.autohotkey.com
; This script displays a popup menu in response to briefly holding down
; the middle mouse button.  Select a menu item by left-clicking it.
; Cancel the menu by left-clicking outside of it.  A recent improvement
; is that the contents of the menu can change depending on which type of
; window is active (Notepad and Word are used as examples here).

; You can set any title here for the menu:
MenuTitle = Select the below options: ;create menu title


SetFormat, float, 0.0 ;not required
SetBatchLines, 10ms ;not necessary
SetTitleMatchMode, 2 ;required for dynamic menu
#SingleInstance, Force


;___________________________________________
;_____Menu Definitions______________________

; Create / Edit Menu Items here.
; You can't use spaces in keys/values/section names.

; Don't worry about the order, the menu will be sorted.

MenuItems = 1)Screenshot1 or Screenshot2 State/2)SpeedUpDown or UndoRedo_State/3)CopyCut or CopylinkCopyCut State/4)MediaPlay4All or MediaPlay4Nox State/5)MediaKey4OneNote or MediaKey4All State/6)Mouse_Middle_Button State/7)Exit Application ;create menu items separated by /

;___________________________________________
;______Dynamic menuitems here_______________

; Syntax:
;     Dyn# = MenuItem|Window title

Dyn1 = Lecture Recordings|- OneNote ;create dynamic menu item and window title for the menu to show up separated by |


;~ Dyn3 = SciTE|SciTE4AutoHotkey ;reserved to demo how dynamic menu item can be created

;___________________________________________

Exit


;___________________________________________
;_____Menu Sections_________________________

; Create / Edit Menu Sections here.

1)Screenshot1orScreenshot2State: ;create non-spaced labels for menu items
{
	scrstate := !scrstate
	if (scrstate=0)
		{
			MsgBox, 262144, Screenshot Key Press,
			(
				Screenshot  - 2 press
				`nRepeat last - 1 press
			) 
		}
	else if (scrstate=1)
		{
			MsgBox, 262144, Screenshot Key Press,
			(
				Screenshot  - 1 press
				`nRepeat last - 2 press
			)
		} 	
}
Return

2)SpeedUpDownorUndoRedo_State:
{
	spustate := !spustate
	if (spustate=0)
		{
			MsgBox, 262144, Speed up/down,
			(
				^ - speed up
				`nv - speed down
			) 
		}
	else if (spustate=1)
		{
			MsgBox, 262144, undo/redo,
			(
				^ - redo
				`nv - undo
			) 
		} 
}
Return

3)CopyCutorCopylinkCopyCutState:
{
	cpcstate := !cpcstate
	if (cpcstate=0)
		{
			MsgBox, 262144, copy/cut,
			(
				copy - 1 press
				`ncut  - 1 press
			) 
		}
	else if (cpcstate=1)
		{
			MsgBox, 262144, copylink/copy/cut,
			(
				copylink(onenote) - 1 press
							 `ncopy - 2 press
							  `ncut - 3 press
			) 
		} 
}
Return

4)MediaPlay4AllorMediaPlay4NoxState:
{
	mdastate:=!mdastate
	SoundBeep, 300, 700
	if (mdastate = 1)
		{
			SplashTextOn,250,60,,Play/Pause for nox
			Sleep 400
			SplashTextOff
			if (fnstate = 0)
				{
					Menu, Tray, Icon, fndisableone_nox.ico
				}
			else if (fnstate = 1)
				{
					Menu, Tray, Icon, fnenableone_nox.ico
				}
		}
	else if (mdastate = 0)
		{
			SplashTextOn,250,60,,Play/Pause for all 
			Sleep 400
			SplashTextOff
			if (fnstate = 0)
				{
					Menu, Tray, Icon, fndisableone_all.ico
				}
			else if (fnstate = 1)
				{
					Menu, Tray, Icon, fnenableone_all.ico
				}
		}
}
Return

5)MediaKey4OneNoteorMediaKey4AllState:
{
	mdkystate := !mdkystate
	if (mdkystate=0)
		{
			MsgBox, 262144, Media_Play_Pause,
			(
				Play/Pause - Play/Pause
			) 
		}
	else if (mdkystate=1)
		{
			MsgBox, 262144, Media_Play_Pause,
			(
				Play/Pause - ctrl + shift + 6
			) 
		} 
}
Return

6)Mouse_Middle_ButtonState:
{
	mbtnstate := !mbtnstate
	SoundBeep, 565, 600
	if (mbtnstate=0)
		{
			MsgBox, 262144, Mouse Middle Button,
			(
				Mbutton - Feature On
			) 
		}
	else if (mbtnstate=1)
		{
			MsgBox, 262144, Mouse Middle Button,
			(
				Mbutton - Feature Off(original)
			) 
		} 
}
Return

7)ExitApplication:
{
	SplashTextOn,150,40,,Exit Script
	Sleep 400
	SplashTextOff
	ExitApp
}
Return

LectureRecording:
Explorer = %A_WinDir%\explorer.exe /n,/e,
Foldexir = C:\Users\amana\Music\Lecture Recordings
Run, %Explorer%"%Foldexir%"
Return


;~ SciTE: ;reserved to demo how dynamic menu item can be created
;~ MsgBox, this is a dynamic entry (SciTE)
;~ Return

;___________________________________________
;_____Hotkey Section________________________
;=======================================================================================
;automatically going to turn on because it will be inside if and else statement ; currtly not possibl
;=========================================================================================
k::
;prepares dynamic menu

DynMenu =
Loop
{
	IfEqual, Dyn%A_Index%,, Break ;break out of loop if DynX is empty

	StringGetPos, ppos, dyn%A_Index%, | ;separate out dynamic menu by menu name and window name
	StringLeft, item, dyn%A_Index%, %ppos%
	ppos += 2
	StringMid, win, dyn%A_Index%, %ppos%, 1000
	
	IfWinActive, %win%, ;add dynamic menu only if the window is active
		DynMenu = %DynMenu%/%item%
}


;Joins sorted main menu and dynamic menu
Sort, MenuItems, D/
TempMenu = %MenuItems%%DynMenu%


;clears earlier entries
Loop
{
	IfEqual, MenuItem%A_Index%,, Break
	MenuItem%A_Index% =
}

;creates new entries
Loop, Parse, TempMenu, /
{
	MenuItem%A_Index% = %A_LoopField%
}

;creates the menu
Menu = %MenuTitle%
Loop
{
	IfEqual, MenuItem%A_Index%,, Break
	numItems ++ ;variable to store number of menu items (counted by loop iterations)
	StringTrimLeft, MenuText, MenuItem%A_Index%, 0 ;not sure why this is here
	Menu = %Menu%`n%MenuText%
}

MouseGetPos, mX, mY
Hotkey, ~LButton, MenuClick ;convert LButton to a hotkey
Hotkey, ~LButton, On ;enable the hotkey if it is currently disabled
ToolTip, %Menu%, %mX%, %mY% ;show tooltip of menu at current cursor loc
WinActivate, %MenuTitle% ;required to by default activate the tooltip to prepare for the next mouse click
Return

MenuClick:
Hotkey, ~LButton, Off ;disable the hotkey if it is currently enabled
IfWinNotActive, %MenuTitle% ;if you clicked elsewhere and so tooltip is not the active window, otherwise you clicked on the tooltip so skip these lines
{
	ToolTip
	Return
}

MouseGetPos, mX, mY
ToolTip
;use msgbox % mY to see the math result
mY += 10	;space after which first line starts | adjustment may be required (increase number to start further down from the top of tooltip)
;~ msgbox % mY
mY /= 23	;space taken by each line | adjustment may be required (decrease number to narrow down the height of each row and vice versa)
;~ msgbox % mY
IfLess, mY, 1, Return ;do nothing if the number is less than 1, i.e. you clicked the title area
IfGreater, mY, %numItems%, Return ;do nothing if mY exceeds the number of menu items
StringTrimLeft, TargetSection, MenuItem%mY%, 0
StringReplace, TargetSection, TargetSection, %A_Space%,, A ;remove all spaces
Gosub, %TargetSection%
Return

I wanted to include the above code under this code but I failed so I decided to go other way.

Return to “Ask for Help (v1)”

Who is online

Users browsing this forum: s1nbad and 265 guests