delphi - 如何使用Delphi在控制台应用程序中显示进度条?

标签 delphi console

我想在一个漫长的过程中在我的控制台应用程序中显示某种动画,但不知道如何做到这一点。

我已经做了一项研究,但我找到的解决方案没有引起我的兴趣,或者我不愿意理解它们。

我的应用程序加载一个文本文件,并通过搜索要替换的单词来逐行遍历所有行。

它可以是进度条或任何循环动画。

最佳答案

这是一个示例,它将在循环中生成消息Processing X of Y (Z%) ...,延迟表示在循环中执行某项操作所花费的时间。显然,这是一个人为的例子,但它显示了一种可能性。 (同样显然,您可以将循环上限的值和消息中的 Y 替换为有意义的值,例如 TStringList.Count。)

program Project1;

{$APPTYPE CONSOLE}

uses
  System.SysUtils;

var
  i: Integer;
  StopValue, Pct: Integer;

(* 
  #13 is a carriage return, which moves the cursor back to the
  left side of the console without adding a line feed (#10). It
  allows writing on the same line over the same content without
  moving to the next line. See the demo output.
*)
const
  StatusMsg = #13'Processing %d of %d (%d%%) ...';

begin
  StopValue := 150;     // Replace with your upper limit, e.g. StringList.Count
  for i := 1 to StopValue do
  begin
    Pct := Trunc((i * 1.0 / StopValue) * 100);
    Write(Format(StatusMsg, [i, StopValue, Pct]));
    (****************************************************************
      Note: The call to Sleep here is only to introduce an artificial
      delay in the loop in order to allow the progress to be seen. 
      Otherwise, the empty loop runs so fast that it's not clear when
      the progress increments are shown.

      Clearly, you would replace the call to Sleep with your code to
      actually do some work, such as processing each line of the text
      file.

      Explained in detail for clarity, as some commenters have indicated
      they're not capable of understanding why a call to Sleep is used
      here, so adding this unnecessarily large comment is needed for them.
    ****************************************************************)
    Sleep(250);
  end;
  Write(#13'Processing complete. Press Enter to quit.');
  ReadLn;
end.

进度指示器快照

enter image description here

关于delphi - 如何使用Delphi在控制台应用程序中显示进度条?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47230536/

相关文章:

colors - 如何使用 D 将颜色打印到控制台中?

ruby-on-rails - 我可以以只读模式打开 rails 控制台吗?

ruby-on-rails - 数据库记录总是返回 'nil'

delphi - 如何将标准 Windows 信息图标很好地绘制到页面控件选项卡的索引

Delphi 64 位 Indy OpenSSL 库

multithreading - 线程加工的选择正确吗?

.net - 如何使用Delphi 7检测.net框架版本

c++ - Windows 7 中的临界区问题

c# - 在 WPF 应用程序中,如何覆盖控制台关闭命令?

Delphi:显示窗口而不激活