[comp.lang.pascal] Inputting numbers on graphics screen made simple...

wct@po.CWRU.Edu (William C. Thompson) (06/22/91)

{ This little piece of code should suit just nicely to read
  characters in from the graphics screen. }

procedure readgstr(x,y: word; maxlen: byte; var s:string);
uses crt,graph;
{ x,y are coordinates for leftmost character of the input string }
{ maxlen is the maximum length of the string s }
const
  spacing=<number of pixels each character should be seperated by>;
  foreground=<color of foreground writing>;
  background=<color of background>;
var
  state: byte;
  ch: char;
  
  function getoneof(s:string):char; 
  { waits for user to input a character contained in string s }
  begin
    repeat
      ch:=readkey
    until pos(ch,s)>0;      { ch is contained in s }
    getoneof:=ch
  end;

begin
  <set appropriate text style here>
  setcolor(foreground);
  state:=1;
  s:='';
  for i:=1 to maxlen do s:=s+' ';
  repeat
    ch:=getoneof('AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'+
      '1234567890-_+=!@#$%^&*()~`''";:/?.,<>][{}\|'+#8+#13);
    if (ch=#8) and (state>1) then begin
      setcolor(background);
      outtextxy(x+spacing*(state-1),y,s[state]);
      s[state]:=' ';
      state:=state-1;
      setcolor(foreground)
      end
    else if (ch=#13) then state:=maxlen+2
    else if state<maxlen+2 then begin 
      s[state]:=ch;
      outtextxy(x+spacing*(state-1),y,s[state]);
      state:=state+1
      end
  until state=maxlen+2;
  { now chop trailing spaces off of s }
  while (length(s)>0) and (s[length(s)]=' ') do delete(s,length(s),1)
end;


Explanation: State is used to keep track of the status of your entry.
When state is in [1..maxlen], you are allowed to input more characters.
When state=maxlen+1, that indicates you can only delete characters.
When state=maxlen+2, you have completed entering characters.

I have used something very similar in the past, and it looks fine to
me.  I know that there are some more sophisticated ways of doing some
of these things, but I tried to keep it simple.

I have similar routines (completed & tested) for sophisticated entering 
of strings (insert and all) from crt mode if anyone is interested.

I apologize for the bizzare form of indentation, but I fell in
love with it and it's hard to go back...
-- 
William C. Thompson  "And you run and you run to catch up with the sun, but
wct@po.cwru.edu      it's sinking, racing around to come up behind you again."
Michelson 620D x2080  - Soon to be Rich and Famous Published Pascal God
A.K.A. Kaiser - Minister of Truth - Master of Time, Space, and Dimension, ^