如何在不使用 3rd 方库的情况下覆盖 Windows 本机 C++ 控制台应用程序中控制台的相同部分?

2022-01-11 00:00:00 windows console c++

我有一个控制台应用程序需要显示项目的状态,但与其疯狂地滚动文本,我宁愿看到当前状态一直显示在同一行上.举个例子:

I have a console app that needs to display the state of items, but rather than having text scroll by like mad I'd rather see the current status keep showing up on the same lines. For the sake of example:

正在运行... nn% 完成
缓冲区大小:bbbb 字节

应该是输出,其中nn"是当前完成百分比,bbbb"是缓冲区大小,在控制台的同一行上定期更新.

should be the output, where 'nn' is the current percentage complete, and 'bbbb' is a buffer size, updated periodically on the same lines of the console.

我采用的第一种方法只是在打印新状态之前将正确数量的退格键打印到控制台,但这有一个令人讨厌的闪烁,我想摆脱它.我还想坚持使用标准库或 MS 提供的功能 (VC 8),以免为这个简单的需求引入另一个依赖项.

The first approach I took simply printed the correct number of backspaces to the console before printing the new state, but this has an obnoxious flicker that I want to get rid of. I also want to stick to either standard library or MS-provided functionality (VC 8) so as not to introduce another dependency for this one simple need.

推荐答案

你可以使用 SetConsoleCursorPosition.您需要调用 GetStdHandle 来获取输出缓冲区的句柄.

You can use SetConsoleCursorPosition. You'll need to call GetStdHandle to get a handle to the output buffer.

相关文章