0

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.

jjoIV
  • 173
  • 7
  • 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. – Kuba Oct 20 '22 at 10:30
  • 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. – Kuba Oct 20 '22 at 10:31
  • 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. – jjoIV Oct 20 '22 at 22:06
  • The point is that the question sounds like a duplicate and if you object I'd like you to explain why. – Kuba Oct 21 '22 at 07:00
  • Fine. Feel free to mark this as a duplicate of some very old questions that have been closed. – jjoIV Oct 21 '22 at 23:00
  • I was thinking about one of those which are linked there and are open. And about moving your answer there so that everything is in one place. – Kuba Oct 22 '22 at 05:46

1 Answers1

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.

Module[{nb},
  Clear[newName];
  nb =
   CreateDialog[
    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];
  While[Not[StringQ[newName]]]
];
Print["Proceed with newName = ", newName]

Tested in Mathematica v12.xx and v13.xx

jjoIV
  • 173
  • 7