8

I am trying to create a spinner / wait cursor in a Delphi console application. I can do it but I am sure the code can be streamlined / improved significantly. Please forgive the poor code:

Procedure PositionXY( x , y : Integer);
var
 hStdOut: HWND;
 ScreenBufInfo: TConsoleScreenBufferInfo;
 Coord1: TCoord;
 z: Integer;
 Begin
  sleep(100);
  hStdOut := GetStdHandle(STD_OUTPUT_HANDLE);
  GetConsoleScreenBufferInfo(hStdOut, ScreenBufInfo);
  Coord1.X := x;
  Coord1.Y := y;
  SetConsoleCursorPosition(hStdOut, Coord1);
 End;

begin
 while True do  begin
 Write('|');
  PositionXY(0,0);
 Write('/');
  PositionXY(0,0);
 Write('-');
  PositionXY(0,0);
 Write('\');
  PositionXY(0,0);
 end;
 ReadLn;
end.

Thanks in advance Paul

Paul Heinrich
  • 647
  • 1
  • 7
  • 15

3 Answers3

10

This might guide you to some optimizations:

Write('|'#8); Sleep(100);
Write('/'#8); Sleep(100);
Write('-'#8); Sleep(100);
Write('\'#8); Sleep(100);

Hint: The #8 is a BackSpace.

Uwe Raabe
  • 45,288
  • 3
  • 82
  • 130
2

My solution following the answers given and feedback.
Thanks to Uwe and Christopher

const Frame: array[0..3] of char =  ('|','/','-','\');

var   i : Integer;

begin
 while True do  begin
  for i := 0 to Length(Frame)-1 do begin
  Write(Frame[i]+#8); Sleep(100);
 end;
  ///do something
 end;
    ReadLn;
end.

Chose this option to allow for easier change of the chars I.e: Cooler ASCII Spinners?

Community
  • 1
  • 1
Paul Heinrich
  • 647
  • 1
  • 7
  • 15
1

Using your Code i would change it a little,

Procedure WriteXY( x , y : Integer, s : string);
var
 hStdOut: HWND;
 ScreenBufInfo: TConsoleScreenBufferInfo;
 Coord1: TCoord;
 Begin
  hStdOut := GetStdHandle(STD_OUTPUT_HANDLE);
  GetConsoleScreenBufferInfo(hStdOut, ScreenBufInfo);
  Coord1.X := x;
  Coord1.Y := y;
  Write(s);
  SetConsoleCursorPosition(hStdOut, Coord1);
 End;

begin
 while True do  begin
  WriteXY(0,0,'|'); Sleep(100);
  WriteXY(0,0,'/'); Sleep(100);
  WriteXY(0,0,'-'); Sleep(100);
  WriteXY(0,0,'\'); Sleep(100);
 end;
 ReadLn;
end.

This makes WriteXY a bit more use full to me than just PositionXY

Christopher Chase
  • 2,840
  • 6
  • 36
  • 57