How to set focus of a dialog window?
Since Input
is a DialogInput
, it seemed reasonable to peek into Input
's structure to understand how the focus is set. After removing the ReadProtected
attribute I've realized that there is no neat way to do it, as WRI itself has done the reposition of the focus via successive SelectionMove
calls.
This example below is not the original but a modified version, as the original Input
definition only includes one InputField
but no other expressions (like a Button
). Note that it is not documented that you can use Initialization
in dialogs, moreover it is colored red by the syntax highlighter to suggest an invalid option.
DialogInput[{InputField["", String], Button["Ok", DialogReturn[]]},
Initialization :> (FrontEndExecute[{
FrontEnd`SelectionMove[#1, Before, Notebook,
AutoScroll -> False],
FrontEnd`SelectionMove[#1, Next, Cell, 2, AutoScroll -> False],
FrontEnd`SelectionMove[#1, Previous, CellContents,
AutoScroll -> False],
FrontEnd`FrontEndToken[#1, "MovePreviousPlaceHolder"]
}] &), ShowCellBracket -> True, Selectable -> True]
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"]
)
]
What's wrong with Input[""]
?