Suppose I want my code to pop up a dialog window containing an InputField and automatically put the keyboard focus there so it's ready and waiting to accept user input.

I wondered about that.

It's not hard to find multiple StackExchange entries showing that others wondered the same thing (e.g., How to set focus of a dialog window?).

I looked at but was not satisfied with the answers so I came up with my own, which is described below.

  • $\begingroup$ If you are not happy with given answers you can add yours, isn't this topic a duplicate? You can make it less duplicate but explaining why do we need a separate one. $\endgroup$
    – Kuba
    Oct 20, 2022 at 10:30
  • $\begingroup$ Btw, your answer does not work for me, maybe OS/race condition dependent. The caret is not shown in the input field. And I guess the SelectionMove approach will need to be adapted if the layout of the dialog changes, right? Additionally, it does not handle Cancel/Close. $\endgroup$
    – Kuba
    Oct 20, 2022 at 10:31
  • $\begingroup$ Thanks for the feedback. #1. I didn't regard the topic as a duplicate because the previous related entries that I found seemed similar but IMHO not quite the same. FWIW, also pretty old. #2. I just verified that the method works on versions 11.3, 12.0, 12.1, 12.2, 12.3, 13.0, and 13.01, but, alas, fails on 13.1. Apparently something changed. Maybe there's a fix but I haven't found it yet. $\endgroup$
    – jjoIV
    Oct 20, 2022 at 22:06
  • $\begingroup$ The point is that the question sounds like a duplicate and if you object I'd like you to explain why. $\endgroup$
    – Kuba
    Oct 21, 2022 at 7:00
  • $\begingroup$ Fine. Feel free to mark this as a duplicate of some very old questions that have been closed. $\endgroup$
    – jjoIV
    Oct 21, 2022 at 23:00

1 Answer 1


Running the demo code below pops up a dialog window with an InputField that returns a String. The combined effect of the two SelectionMove commands is to put the focus inside the InputField. The While step spin-waits until an acceptable input has been entered. After that normal execution proceeds.

  nb =
    Column[{TextCell["Enter new name", 20], 
      Row[{InputField[Dynamic[newName], String, Alignment -> Right]}, 
       BaseStyle -> 16, Alignment -> Center],
      DefaultButton[DialogReturn[]]}, Alignment -> Center],
    Modal -> True(* Block other Mathematica windows until closed. *)
  (* Move window focus to input field, then wait until new name has been entered. *)
  SelectionMove[nb, Before, CellContents];
  SelectionMove[nb, Next, TextLine];
Print["Proceed with newName = ", newName]

Tested in Mathematica v12.xx and v13.xx


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.