A customer recently asked how to read some input from the user in XJEase. The next major release of XJTAG (probably numbered 2.4) will contain a new XJEase function INPUTBOX that makes doing this much simpler. In the meantime, I thought I might outline some code that accomplishes the same thing in the current version.
The core of the code is a loop that simply calls the WAITKEY function to read a character of input at a time, until a carriage return is read. As each character is read it is appended to a string that will be returned and also printed to the screen.
STRING text; INT key; DO key := WAITKEY(); WHILE key := ASC("\n") && key != ASC("\r"); // ignore any control characters (ASCII value less than 0x20) IF key >= 0x20 THEN PRINT(CHAR(key)); text := text + CHAR(key); END; END;
This works reasonably well until the user makes a mistake and wants to backspace. Handling backspace requires us to print the backspace character and remove the last character from the string that we’re building. We can also check the current length of the input string and not allow the user to backspace beyond its start.
INPUTBOX(STRING prompt, STRING title, STRING default)(STRING input) STRING text := default; INT key; INT width; ALERT(); IF title != "" THEN PRINT(title, "\n"); END; PRINT(prompt); DO key := WAITKEY(); WHILE key := ASC("\n") && key != ASC("\r"); IF key = ASC("\b") THEN width := WIDTHOF(text); IF width > 0 THEN PRINT("\b"); IF width = 1 THEN text := ""; ELSE text := text[width-2..0]; END; END; ELSIF key >= 0x20 THEN // ignore any control characters (ASCII value less than 0x20) PRINT(CHAR(key)); text := text + CHAR(key); END; END; PRINT("\n"); input := text; END; GetInput()() STRING input; input := INPUTBOX("Please enter some input and press Enter:", "Input", ""); PRINT("\nGot \"", input, "\"\n"); END;
The full function appears below, plus an example of its use. It is named INPUTBOX and has the same signature as the upcoming XJEase built-in function, which means once the new version of XJTAG arrives, this function can be deleted and the code will then continue to work. The 3 arguments are the prompt to display, a title and a string that is presented as the default (can be left as an empty string). Note that the example below simply prints the title out, whereas the real INPUTBOX will create a proper dialog box.Note also the use of the ALERT function. If you have more than one XJLink attached in XJRunner, then the output from each is displayed in its own tab; the ALERT function causes the application to draw attention to any tab that requires attention. In XJDeveloper or in XJRunner with just one XJLink attached, then the function has no effect.
Leave A Comment