Jump to content

Sky Slate Blueberry Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate
Photo

InputBox() - easy & powerful InputBox implementation


  • Please log in to reply
11 replies to this topic
berban
  • Members
  • 202 posts
  • Last active: Jun 07 2016 02:58 AM
  • Joined: 30 Dec 2009
InputBox() - easy & powerful InputBox implementation



Gathering textual user input is a common task, and using AutoHotkey's InputBox command is a great simple way to do this. The following function corrects many shortcomings of the InputBox command, adds a few features, and makes it easier to use. You should have this script in your library if you use InputBoxes.

Posted ImagePosted ImagePosted Image


Posted ImagePosted ImagePosted ImagePosted ImagePosted ImagePosted ImageInputBox(ByRef OutputVar, Title="", Text="", Default="`n", Keystrokes="")


Usage: The most common way to use this function is as follows:
#g::
If InputBox(Var)
	Return
MsgBox, You entered the text "%var%" and submitted the InputBox. Now the script can do something with this input.
Return

Usually, an InputBox allows the user the opportunity to either enter text OR cancel the command then and there if they wish. Since the function returns the ErrorLevel of the InputBox command, this is an easy way to return if the user cancels the box.


Posted Imagehttps://ahknet.autoh...izontalLine.png

Parameters:[*:f548ouio]OutputVar: This is the variable in which the result will be stored. Leave it unquoted since the parameter is ByRef. Basically it's analogous to the first parameter in the regular InputBox command except that in this case the variable is not changed if the user cancels the box.[*:f548ouio]Title: The title of the dialog box. The default title is "NameOfScript: Input"[*:f548ouio]Text: The text prompt to display. Normally the box is only tall enough for the titlebar, textbox, and buttons, but if you put text here the function will try to automatically make room for it. It judges by the number of newlines (`n) present, so just add more at the end of the "text" param if the box doesn't end up being tall enough for all the text.[*:f548ouio]Default: The text already present in the input field.
The default is "`n", which is a placeholder that means that the input will contain whichever text was last submitted to that particular input box, blank if none. The function distinguishes between prior input boxes based on title. So it pays to give your InputBoxes unique titles, because that way a different last input is remembered for each.
Sometimes, it is desirable to change the title of a box while maintaining the same functionality. Any text after " - " does not affect the input box memory, for instance, "Name - John Doe" and "Name - Jane Smith" will be considered the same.[*:f548ouio]
Keystrokes: Keystrokes to send to the input field before the user interacts with it. Normally, the entirety of the default text is selected. The keystrokes parameter can be used to change this, for instance, to select a file name and exclude its extension as happens when you press F2 in Windows 7.
https://ahknet.autoh...izontalLine.png

Why use InputBox()?[*:f548ouio]Shortens code required to make an InputBox. Also, functions are generally more versatile than commands.
[*:f548ouio]InputBoxes are always-on-top.
[*:f548ouio]Simplifies the long and confusing list of parameters that come with the built-in command by assuming some (x, y, width, height) and removing others (font, HIDE, timeout).https://ahknet.autohotkey.com/~berban/spacer.pnghttps://ahknet.autohotkey.com/~berban/spacer.pnghttps://ahknet.autohotkey.com/~berban/HorizontalLine.png

Some working examples:
While !InputBox(VarA, "VarA") and !InputBox(VarB, "VarB") ;continues until one returns an error
	MsgBox, You entered "%VarA%" and "%VarB%"
MsgBox, You cancelled one of the above InputBoxes.

;Dialog box to create a new file on your desktop
!^n::
NewFile = NewFile.txt
Loop
	If InputBox(NewFile, "New File...", A_Index = 1 ? "" : """" NewFile """ already exists.", NewFile, "{Home}+{Right " InStr(NewFile, ".", 0, 0) - 1 "}")
		Return
	Else If !FileExist(A_Desktop "\" NewFile)
		Break
FileAppend, , %A_Desktop%\%NewFile%
Run, notepad.exe "%A_Desktop%\%NewFile%"
Return

;One line google search!
;Hold CTRL while submitting to search AutoHotkey.com
;Hold SHIFT while submitting to do an I'm Feeling Lucky™ search.
;Try doing both together
F4::Run, % InputBox(SearchTerms, "Google™ Search") ? "" : "http://www.google.com/search?q=" RegExReplace(SearchTerms, "\s+", "+") (GetKeyState("Ctrl", "P") ? "+site:AutoHotkey.com" : "") (GetKeyState("Shift", "P") ? "&btnI=3564" : "")

https://ahknet.autoh...izontalLine.png

Code:
InputBox(ByRef OutputVar="", Title="", Text="", Default="`n", Keystrokes="") ;http://www.autohotkey.com/forum/viewtopic.php?p=467756
{
	Static KeysToSend, PID, HWND, PreviousEntries
	If (A_ThisLabel <> "InputBox") {
		If HWND
			SetTimer, InputBox, Off
		If !PID {
			Process, Exist
			PID := ErrorLevel
		}
		If Keystrokes
			KeysToSend := Keystrokes
		WinGet, List, List, ahk_class #32770 ahk_pid %PID%
		HWND = `n0x0`n
		Loop %List%
			HWND .= List%A_Index% "`n"
		If InStr(Default, "`n") and (UsePrev := True)
			StringReplace, Default, Default, `n, , All
		If (Title = "")
			Title := SubStr(A_ScriptName, 1, InStr(A_ScriptName, ".") - 1) ": Input"
		SetTimer, InputBox, 20
		StringReplace, Text, Text, `n, `n, UseErrorLevel
		InputBox, CapturedOutput, %Title%, %Text%, , , Text = "" ? 100 : 116 + ErrorLevel * 18 , , , , , % UsePrev and (t := InStr(PreviousEntries, "`r" (w := (u := InStr(Title, " - ")) ? SubStr(Title, 1, u - 1) : Title) "`n")) ? v := SubStr(PreviousEntries, t += (u ? u - 1 : StrLen(Title)) + 2, InStr(PreviousEntries "`r", "`r", 0, t) - t) : Default
		If !(Result := ErrorLevel) {
			OutputVar := CapturedOutput
			If t
				StringReplace, PreviousEntries, PreviousEntries, `r%w%`n%v%, `r%w%`n%OutputVar%
			Else
				PreviousEntries .= "`r" w "`n" OutputVar
		}
		Return Result
	} Else If InStr(HWND, "`n") {
		If !InStr(HWND, "`n" (TempHWND := WinExist("ahk_class #32770 ahk_pid " PID)) "`n") {
			WinDelay := A_WinDelay
			SetWinDelay, -1
			WinSet, AlwaysOnTop, On, % "ahk_id " (HWND := TempHWND)
			WinActivate, ahk_id %HWND%
			If KeysToSend {
				WinWaitActive, ahk_id %HWND%, , 1
				If !ErrorLevel
					SendInput, %KeysToSend%
				KeysToSend =
			}
			SetTimer, InputBox, -400
			SetWinDelay, %WinDelay%
		}
	} Else If WinExist("ahk_id " HWND) {
		WinSet, AlwaysOnTop, On, ahk_id %HWND%
		SetTimer, InputBox, -400
	} Else
		HWND =
	Return
	InputBox:
	Return InputBox()
}


~ Created with Quick Functions for Forums by berban ~

sal
  • Members
  • 35 posts
  • Last active: Jun 16 2013 06:39 PM
  • Joined: 19 Feb 2011
berban wrote

Why use InputBox()?
Shortens code required to make an InputBox. Also, functions are generally more versatile than commands.
InputBoxes are always-on-top
Simplifies the long and confusing list of parameters that come with the built-in command by assuming some (x, y, width, height) and removing others (font, HIDE, timeout)


I totally agree with you. usually we use just the title,prompt and default value if any so here was my inputbox funtion. I will test yours I am sure
it is much better
thanks for sharing :D

;  inputbox sample
result := inputbox("This is a title","This is the prompt","this is the default 
text replace it if you wish")
msgbox %result%

; function
InputBox(Title="",Prompt="",Default="",HIDE="",Width=250,Height=180,X="",Y="",Font="",Timeout= "")
{
   InputBox, v, %Title%, %Prompt%, %HIDE%, %Width%, %Height%, %X%, %Y%, , %Timeout%, %Default%
   Return, v
}


eltunene
  • Members
  • 11 posts
  • Last active: Jul 19 2012 12:03 AM
  • Joined: 19 Jul 2012
Dear Berban,

I know this is not directly related to the subject, but I am trying to make an input box for adding text to a txt database, and it works, but I intended to put a variable in the "prompt" area, and it worked sometimes, but maybe I changed something, because now it will not work, nothing appears in the prompt area. However, I added a MsgBox and used the same variable (clipboard, by the way) and it will show whatever is in the variable, not its name. What am I doing wrong?

I am new to ahk, but I find it fascinating.

Thanks,

Jess


#a::

clipboard = 


Send ^c

InputBox, OutputVar, STLator V, %clipboard%, ,1000

TotalVar = %clipboard%|%OutputVar%

MsgBox, %TotalVar%

FileAppend, %TotalVar%`n, C:\Memorias STLator\Test STLator Memory003.txt


berban_
  • Members
  • 202 posts
  • Last active: Aug 05 2014 11:52 PM
  • Joined: 16 Mar 2011
Dear Jess,

Happy to help! I'm not 100% sure what the issue here is but I'm going to guess it's a problem with the clipboard. The windows clipboard is finicky and not easy to work with using AutoHotkey. Often it takes a small amount of time (under half a second) for ctrl+c to actually capture text into the Clipboard variable. So I'd recommend doing something like this:

#a::

clipboard = 


Send ^c
[color=red]Sleep 400 ; 400 milliseconds[/color]
InputBox, OutputVar, STLator V, %clipboard%, ,1000

TotalVar = %clipboard%|%OutputVar%

MsgBox, %TotalVar%

FileAppend, %TotalVar%`n, C:\Memorias STLator\Test STLator Memory003.txt

You can also try using this function of mine which attempts to address some of the niceties of the windows Clipboard: Clip() - Send and Retrieve Text using the Clipboard • AutoHotkey ...

I don't visit the forums much but you can often find me on the AutoHotkey web chat - it's a good place to stop by if you have a quick question.

eltunene
  • Members
  • 11 posts
  • Last active: Jul 19 2012 12:03 AM
  • Joined: 19 Jul 2012
Wow! It worked! I had the idea the clipboard was capturing the text, since it did appear in the MsgBox, but not in the input box, maybe by the time it went from the input box to the msgbox, it was captured. Tricky, it's true. Thanks a lot!

eltunene
  • Members
  • 11 posts
  • Last active: Jul 19 2012 12:03 AM
  • Joined: 19 Jul 2012
Hey, Berban

The English>Spanish translator is working very well, except when the .txt database contains some symbols, then it kind of goes crazy, repeating the last phrase several times. There must be something I can do, maybe replace the symbols with other characters and then restore them at the end of the AHK procedure.

I'll keep trying. Got any ideas?

Jesse.

berban_
  • Members
  • 202 posts
  • Last active: Aug 05 2014 11:52 PM
  • Joined: 16 Mar 2011
English to spanish translator? Is that the script that you are working on? If so I'd need to see the full script to be of help.
It might be better if you post this in the "Ask for Help" section of the forums; that way, you can start a thread dedicated to the unique problems concerning your script.

burton666
  • Members
  • 186 posts
  • Last active: Jul 05 2017 05:35 AM
  • Joined: 10 Aug 2012

I have a small script like this:

#p::

If !InputBox(VarA, "Order? (last digits?)") and !InputBox(VarB, "Picker?")
send {tab 3}{space}
Loop 

{
stuff...
}

But I can't figure out how to make the script abort when I press the cancel-button on the inputbox.



MasterFocus
  • Moderators
  • 4323 posts
  • Last active: Jan 28 2016 01:38 AM
  • Joined: 08 Apr 2009

EDIT: I misread berban's documentation.

You'd have to do something like this:

If InputBox(...) OR InputBox(...)
    MsgBox, Something was canceled (or timed out). You should abort here.

 

Alternatively, you can try my InputBox() wrapper in a similar way:

If InputBox(...)
    MsgBox, The input was blank and/or the OK button wasn't pressed.

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Antonio França -- git.io -- github.com -- ahk4.net -- sites.google.com -- ahkscript.org

Member of the AHK community since 08/Apr/2009. Moderator since mid-2012.


Chris Eelmaaa
  • Members
  • 1 posts
  • Last active: Dec 04 2014 10:37 AM
  • Joined: 03 Dec 2014

Hi berban_, very useful stuff.

I incorporated that to search from google, as such:

 

NumpadUp::
browser="C:\Program Files (x86)\Mozilla Firefox\firefox.exe"
If InputBox(Var, "Google Search dialog", "Please write a search word, and press 'OK'")
    Return

Run, %browser% "www.google.co.uk/search?q=%var%"
Return

Also, I had to change the height a bit, because 'text' was unreadable otherwise, I increased it by 10 units,
 

Text = "" ? 100 : 126 + ErrorLevel

Btw, a recommendation: in 90% of the cases, the flow is usually like so:
 

If InputBox(...)
    MsgBox, OK button was pressed, do the processing.

Cheers.



bruno
  • Members
  • 635 posts
  • Last active: Nov 04 2015 02:26 PM
  • Joined: 07 Mar 2011

very nice! ;)

#Include InputBox.ahk

#SingleInstance Force
#NoEnv

#f::
Browser=Firefox.exe
If InputBox(Var, "Google Search", "Enter search word:")
Return
Run, %Browser% "www.google.com/search?q=%Var%"
Return


smorgasboard
  • Members
  • 660 posts
  • Last active: Jan 14 2016 08:53 AM
  • Joined: 18 Jul 2012

@Bruno why are you doing this?

for many posts.