My Basic Script

Post your working scripts, libraries and tools
SSpeed
Posts: 23
Joined: 04 Jul 2018, 09:48

My Basic Script

29 Mar 2019, 18:05

Here's the code I made for a friend who is new to AHK.
If any pros wanna help, I'd love to see some improvements to it.

To get started with the script, just include the second script. Hotkeys are near the top of the Background script. Uncomment the hotkeys that you want to try. I hope it helps.

Background script

Code: Select all

; #Include C:\Users\_____\Google Drive\My Scripts\_\#essentials.ahk  ; (tip)
#Include #essentials.ahk  ; (same folder)
; Menu, Tray, Icon, _\icon.ico  ; (tip)
SetCapsLockState, AlwaysOff
SetNumLockState, AlwaysOn
SetScrollLockState, AlwaysOff
OnExit("ExitFunc")
ExitFunc() {
	Show_windows()
	Gosub, dc_restore_window
}


;==========================================
; [ Background script ]
;==========================================

#IfWinActive
; #G:: Google_that()					; ← googles the selected text, or if it's a web address, opens it
; #H:: Hide_window()					; ← hide the active window
; #S:: Show_windows()					; ← unhides all windows
; #T:: Toggle_AlwaysOnTop()				; ← make a window always-on-top, or take it away
; #W:: Run_AHKspy()						; ← launch AHK window spy, which I often use to check the window's information quickly
CapsLock:: Toggle_Favorite_Window()		; ← activate favorite window, or activate last active window
^CapsLock:: Save_Favorite_Window()		; ← set favorite window
; F9:: Get_Color()						; ← get pixel's color
; ^F9:: Save_Coords()					; ← quickly save coords
; F12:: Detect_Change()					; ← shrink a window to tiny size, where the cursor is at, and then unshrink when either:  A) the color at that pixel changes, or  B) the script closes or reloads

; #IfWinActive, ahk_exe sublime_text.exe
; `:: Send, ^l{Delete}					; ← delete line or all lines selected, while sublime text window is active
; ~^S:: Close_Sublime_Popup()			; ← closes the occassional sublime popup when it occurs

#IfWinActive
#E:: Edit								; ← open the code for that script
#R:: Reload								; ← reload the active script
*esc::									; ← panic button
#Esc:: ExitApp							; ← my preferred method to exit a script


;*****************************************************
;
;
;
;
;
;*****************************************************

Google_that() {
	tt := GetText()
	If Not(tt)
		Exit()
	tt := RegExReplace(tt, "^\s+|\s+$")  ; (trim whitespace)
	If RegExMatch(tt, "\w\.[a-zA-Z]+(/|$)")  ; (contains .com etc)
	{
		If SubStr(tt, 1, 4) != "http"
			tt := "http://" . tt  ; (adds http to the web address if needed)
	}else
	{
		If InStr(tt, " ")
		{
			StringReplace tt, tt, %A_Space%, +
			tt := "%22" . tt . "%22"
		}tt := "https www.google.com /search?q="  Broken Link for safety . tt
	}Run %tt%
}
Hide_window() {
	global HiddenWins
	MyWin := WinExist("A")
	If IsWindow("A")
	{
		HiddenWins .= (HiddenWins ? "|" : "") . MyWin
		WinHide ahk_id %MyWin%
		GroupActivate All
	}
}
Show_windows() {
	global HiddenWins
	If (HiddenWins)
	{
		Loop Parse, HiddenWins, |
			WinShow ahk_id %A_LoopField%
		HiddenWins =
	}
}
Toggle_AlwaysOnTop() {
	If Not IsWindow("A")
		return
	WinGetTitle, tt, A
	WinSet AlwaysOnTop, toggle, A
	If (SubStr(tt, 1, 2) = "t ")
		tt := SubStr(tt, 3)
	else
		tt := "t " . tt
	WinSetTitle, A, , %tt%
}
Run_AHKspy() {
	Run, C:\Program Files\AutoHotkey\WindowSpy.ahk
	WinWait, Window Spy, , 2
	WinMove, 920, 0  ;= (move window to top right corner)
}
Toggle_Favorite_Window() {
	global favorite_window
	SetCapsLockState, AlwaysOff
	If Not WinActive("ahk_id " . favorite_window)
		WinActivate("ahk_id " . favorite_window)
	else 
	{
		; winactivate last
		Send {Alt Down}{Tab}
		Sleep, 70
		Send {Alt Up}
	}
}
Save_Favorite_Window() {
	global favorite_window
	favorite_window := WinExist("A")
}
Get_Color() {
	; move mouse away
	MouseGetPos, x, y
	PixelGetColor, last_color, x, y
	If (x > A_screenwidth/2)
		xm := -1 * A_screenwidth/4  ; (move left by a quarter of screen)
	else
		xm := 1 * A_screenwidth/4
	MouseMove, xm, 0, , r
	Sleep, 40
	MouseMove, 0, 0
	; wait briefly
	last_changed =
	Loop, 14  ; (1.4 seconds)
	{
		; (end wait sooner if it seems that the color won't change further)
		PixelGetColor, c, x, y  ; check pixel for color
		If Not ColorMatch(x, y, last_color)  ; if color changes, update last color
		{
			last_changed := A_Index
			PixelGetColor, last_color, x, y
		}If (A_Index-last_changed >= 4)  ; (after color has changed, check for the color to remain constant over .4s interval)
			break
		Sleep, 100
	}  ; save to clipboard
	msg := "If ColorMatch(" . x . ", " . y . ", " . last_color . ")  `; ()`n{`n`n`n}"
	Clipboard := msg
	MouseMove, x, y
	ToolTip("saved to clipboard", 2)
}
Save_Coords() {
	; save points quickly, while ctrl is held down
	While GetKeyState("ctrl", "P")
	{
		KeyWait, F9, D t0.2
		If Not(ErrorLevel)
		{
			If GetKeyState("ctrl", "P")
			{
				MouseGetPos, x, y
				msg .= "	MouseClick, L, " . x . ", " . y . "  `; ()`n	Sleep, 1000`n"
				ToolTip, *
			}KeyWait, F9, t12
		}
	}
	; save to clipboard
	Clipboard := msg
	ToolTip("saved to clipboard", 2)
}
Detect_Change() {
	global
	If (dc_active)
		return
	dc_active := true
	Hotkey, ~#d, On
	Hotkey, ~!Tab, On
	MouseGetPos, dc_x, dc_y, dc_hwnd  ; (get mouse coord, get window ID)
	PixelGetColor, dc_c, dc_x, dc_y  ; (get pixel color)
	CoordMode, Mouse, Relative
	MouseGetPos, dc_xr, dc_yr  ; (get relative mouse coord, because WinSet Region is weird..)
	CoordMode, Mouse, Screen
	dc__xr := dc_xr-1,    dc__yr := dc_yr-1
	WinSet, Region, %dc__xr%-%dc__yr% w3 h3, ahk_ID %dc_hwnd%  ; (tiny size)
	Sleep, 100
	WinSet, AlwaysOnTop, ON, ahk_ID %dc_hwnd%  ; (always-on-top window)
	SetTimer, detect_change, 4000
}
	detect_change:
		If Not ColorMatch(dc_x, dc_y, dc_c)
		{
			SetTimer, detect_change, Off  ; (break loop)
			Gosub, dc_restore_window
		}return
		dc_restore_window:
			If (dc_active)
			{
				WinSet, Region, , ahk_ID %dc_hwnd%  ; (full size)
				WinSet, AlwaysOnTop, Off, ahk_ID %dc_hwnd%  ; (make window not always on top)
				WinActivate, ahk_ID %dc_hwnd%  ; (focus window)
				Hotkey, ~#d, Off
				Hotkey, ~!Tab, Off
				dc_active := false
				SoundBeep(700)
			}return
	~#d:: 
	~!Tab:: 
		If (dc_active)
		{
			If (A_ThisHotkey = "~!Tab")  ; (wait for hotkey button release)
				KeyWait, LAlt, T4
			else If (A_ThisHotkey = "~#d")
				KeyWait, d, T1
			Sleep, 40
			; if dc_window active, then
			WinGetTitle, window, A
			If (window = "ahk_ID %dc_hwnd%")
			{
				; [ full size mode ]
				WinSet, Region, , ahk_ID %dc_hwnd%  ; (full size)
				Sleep, 400
			}else  ; else 
			{
				; [ background mode ]
				; shrink window
				WinSet, Region, %dc__xr%-%dc__yr% W3 H3, ahk_ID %dc_hwnd%  ; (tiny size)
				Sleep, 100
				If (A_ThisHotkey = "~!Tab")
					WinGetTitle, _last_window, A  ; (remembers alt-tab choice)
				; unminimize window, if minimized
				Loop, 2
				{
					WinGet, state, MinMax , ahk_ID %dc_hwnd%
					If (state = -1)
					{
						WinRestore, ahk_ID %dc_hwnd%
						WinWaitActive, ahk_ID %dc_hwnd%, , 1.5
						Sleep, 400
						If (A_ThisHotkey = "~!Tab")
						{
							; activate intended alt-tab window
							WinActivate, _last_window
							Sleep, 400
						}Sleep, 400
					}else
						Break
				}
			}If Not(dc_active)
				WinSet, Region, , ahk_ID %dc_hwnd%  ; (full size)
		}return

Close_Sublime_Popup() {
	static title := "This is an unregistered copy"
	WinWait, % title, , 0.5
	IfWinExist, % title
		WinClose, % title
}



#essentials

Code: Select all

#SingleInstance, Force
#NoEnv
SetWorkingDir, % A_ScriptDir
SendMode, Input
CoordMode, Mouse, Screen
CoordMode, Pixel, Screen
CoordMode, ToolTip, Screen
Send {Shift Up}{Ctrl Up}{Alt Up}
While WinExist("ahk_class #32770", "Error in")  ; (closes ahk error windows)
	WinClose, ahk_class #32770, Error in
Goto #ess_skip


;***************************************************

ColorMatch(x, y, c) {
	If (PixelGetColor(x, y) = c)
		return 1
	return 0
}
ColorWait(x, y, c, time, exitcode:=1) {
	f := Min(.1 * time, 1)  ; speed of occurence  (ie. t1 -> 0.1s,  t10 -> 1s)
	l := time / f
	Loop, % l
	{
		If ColorMatch(x, y, c)
			return 1
		Sleep, % f * 1000
	}If ColorMatch(x, y, c)
		return 1
	; on exit
	If (exitcode = 1)
		Exit()
	ExitApp()
}
GetText(ByRef MyText = "") {  ; (copies the selected text to a variable while preserving the clipboard)
	SavedClip := ClipboardAll
	Clipboard =
	Send ^c
	ClipWait 0.5
	If ErrorLevel
	{
		Clipboard := SavedClip
		MyText =
		return
	}MyText := Clipboard
	Clipboard := SavedClip
	return MyText
}
IsWindow(title) {  ; (check if a window is really a window, and not desktop, taskbar, menu, etc.)
	hwnd := WinExist(title)
	WinGet, s, Style, ahk_id %hwnd%
	return s & 0xC00000 ? (s & 0x80000000 ? 0 : 1) : 0
}
Msgbox(text := "", time := 604800) {
	MsgBox, 262144, ~, % text, % time
}
PixelGetColor(x, y) {
	local
	PixelGetColor, color, x, y
	return color
}
RunAsAdmin() {
	If (A_IsAdmin)
		return
	s := (A_IsUnicode ? "" : "A")
	RegExMatch(DllCall("GetCommandLine" s, "Str"), "^(?|""(?<Exe>[^""]+)""|(?<Exe>[^ ]+))(?: (?<Args>.*))?$", CommandLine)
	DllCall("shell32\ShellExecute" s, "Ptr", 0, "Str", "RunAs", "Str", CommandLineExe, "Str", CommandLineArgs, "Str", A_WorkingDir, "Int", 1)
	ExitApp
}
RandSleep(a, b) {
	Random, rand, a, b
	Sleep, rand
}
Reload() {
	Reload
	Sleep, 40
}
SoundBeep(Frequency) {
	SoundGet, MasterVolume
	(Frequency = 400) ? (v := 48) : (v := 36)  ; (if frequency is 400, then use a higher volume)
	SoundSet, % v  ; (volume range is from 0 to 100)
	SoundBeep, Frequency
	SoundSet, MasterVolume
}
ToolTip(string:="", time:=4, x:="", y:="", whichtooltip:=1) {
	ToolTip, % string, x, y, whichtooltip
	If (whichtooltip = 1)
		whichtooltip := ""
	label := "ToolTip" . whichtooltip . "_Off"
	SetTimer, % label, % time * -1000
}	
	ToolTip2_Off:
	ToolTip_Off:
		tt := SubStr(A_ThisLabel, 8, 1)
		if tt is number
			ToolTip, , , , tt
		else ToolTip
		return

Unminimize(title := "A") {  ; (if minimized, then unminimize)
	WinGet, state, MinMax, % title
	If (state = -1)
	{
		WinRestore, % title
		Sleep, 200
	}
}
WinActivate(title := "A") {
	Unminimize(title)
	WinActivate, % title
}
WinMaximize(title := "A") {  ; (if not maximized, then maximize)
	WinGet, state, MinMax , % title
	If (state <> 1)
		WinMaximize, % title
}
WinMinimize(title := "A") {
	If Not IsWindow(title)
		return
	WinGet, state, MinMax , % title
	If (state <> -1)
		WinMinimize, % title
}
WinWait(title := "A", timeout := 4) {
	WinWait, % title, , timeout
	If ErrorLevel
		Exit()
}
WinWaitActive(title := "A", timeout := 4) {
	WinWaitActive, % title, , timeout
	If ErrorLevel
		Exit()
}
Exit() {
	SoundBeep(400)
	Exit
}
ExitApp() {
	SoundBeep(400)
	ExitApp
}
ExitApp:
	SoundBeep(400)
	ExitApp


;***************************************************

#ess_skip:


BannerStore
Posts: 16
Joined: 06 Sep 2017, 19:29

Re: My Basic Script

22 Jan 2020, 18:36

This is awesome. Not sure how it works but will try to make it work. Thanks!
User avatar
tidbit
Posts: 1155
Joined: 29 Sep 2013, 17:15
Location: USA

Re: My Basic Script

23 Jan 2020, 19:22

Pro tip: want more 'customers'? You should tell people what it does. Only a couple people (you and friend) know what it does and why someone might want it. People don't like downloading and running unknown programs

Same goes for this topics title. "My Basic Script" is not very informative as to what we are potentially downloading
rawr. fear me.
*poke*
Is it December 21, 2012 yet?
SSpeed
Posts: 23
Joined: 04 Jul 2018, 09:48

Re: My Basic Script

25 Jan 2020, 21:12

*discontinued*

otherwise I'd add my favorite new feature, myCommandLine - call actions via custom keywords. (ex. input 'su' to open Sketchup, or 'gd' to open Google Drive folder, etc.)

I was just sharing the work I had accumulated over the years, minus the more niche stuff. I did my best, me + the internet... Good luck to the next generation I guess..
User avatar
Bugz000
Posts: 63
Joined: 30 Sep 2013, 10:01

Re: My Basic Script

25 Jan 2020, 21:48

would be great to know what we are missing out on though just saying
Image
Image
[14/10/2019][03:06:09] <@tidbit> so, 8 years old. thats way too young for a human centipede.
[29/10/2019][01:48:42] <@tidbit> it should be a cloaca

Return to “Scripts and Functions”

Who is online

Users browsing this forum: Bing [Bot], malcev, Xeo786 and 52 guests