Skip to main content

front end - How to set focus of a dialog window?


I have a dialog, which, when pops up, requests input from the user. How can I set the window up that the focus is on the InputField of the new window (i.e. the caret stands in the InputField), so that when the user starts typing, it is immediately registered by the field? At the moment, I have to click inside the field first to make it the active control on screen.


DialogInput[{InputField["", String], Button["Ok", DialogReturn[]]}]

Answer



After István Zachar's points, I was investigating Input definitions to learn more. It seams that 2 years later WRI changed approach from SelectionMove based to more automatic BoxReferenceFind.


usage


So what we only have to do is to set BoxID option for fields of interest and find those references when we want, with:


MathLink`CallFrontEnd[

FrontEnd`BoxReferenceFind[
FE`BoxReference[
_NotebookObject, {{ID_String}},
FE`BoxOffset -> {FE`BoxChild[1]},
FE`SearchStart -> "StartFromBeginning"
]
]
]

This is a way more flexible approach, e.g. you can easily put InputField somewhere else and you don't have to change SelectionMove steps to get there.



example


DynamicModule[{name = "", surname = "", setFocus}
, Column[{
InputField[Dynamic@name, String, BoxID -> "name"]
, InputField[Dynamic@surname, String, BoxID -> "surname"]
, Button["setFocusToFirst", setFocus[EvaluationNotebook[], "name"]]
}]
, SynchronousInitialization -> False
, Initialization :> (
setFocus[nb_, ID_] := MathLink`CallFrontEnd[

FrontEnd`BoxReferenceFind[ FE`BoxReference[
nb
, {{ID}}
, FE`BoxOffset -> {FE`BoxChild[1]}
, FE`SearchStart -> "StartFromBeginning"
]]
]
; setFocus[EvaluationNotebook[], "surname"]
)
]

Comments