For version 9 or above, one can use CellPrint
(or simply Print
, as it is a specific case of CellPrint
) which does not move the selection and thus preserves the focus on the InputField
.
EventHandler[InputField["", String],
{"ReturnKeyDown" :> CellPrint[Cell["test", "Output"]]}
]
Since the above code only works in v9, here is an equivalent with tedious selection-manipulation. First I set up the EventHandler
as a cell, so that I can add a cell tag ("input"
) to it. This is necessary to be able to navigate the selection back (NotebookFind
) after using Enter in the InputField
, as one doesn't know how many extra cells will be generated. Using NotebookSelection
however can only get us before the InputField
, but not inside. To move the caret inside, a specific FrontEndToken
is used ("MovePreviousPlaceHolder"
). Perhaps someone knows a shorter method.
nb = EvaluationNotebook[];
CellPrint[ExpressionCell[
EventHandler[InputField[Dynamic@test, String], {"ReturnKeyDown" :> (
SelectionMove[nb, After, Notebook, AutoScroll -> False];
NotebookWrite[nb, Cell[test, "Output"], AutoScroll -> False];
NotebookFind[nb, "input", Previous, CellTags, AutoScroll -> False];
SelectionMove[nb, Before, CellContents, AutoScroll -> False];
FrontEndExecute@FrontEnd`FrontEndToken[nb,
"MovePreviousPlaceHolder", AutoScroll -> False];
SelectionMove[nb, After, Characters, AutoScroll -> False];
)}],
"Output", CellTags -> {"input"}]]
SelectionMove[EvaluationNotebook[], After, Cell];
inested of..Notebook, All]
works like you want? $\endgroup$InputField
. I will add that to the question. But yes that does partially work. $\endgroup$