How can I overwrite the same portion of the console in a Windows native C++ console app, without using a 3rd Party library?

前端 未结 5 896
忘了有多久
忘了有多久 2020-12-09 11:31

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

相关标签:
5条回答
  • 2020-12-09 11:48

    If you print using \r and don't use a function that will generate a newline or add \n to the end, the cursor will go back to the beginning of the line and just print over the next thing you put up. Generating the complete string before printing might reduce flicker as well.

    UPDATE: The question has been changed to 2 lines of output instead of 1 which makes my answer no longer complete. A more complicated approach is likely necessary. JP has the right idea with the Console API. I believe the following site details many of the things you will need to accomplish your goal. The site also mentions that the key to reducing flicker is to render everything offscreen before displaying it. This is true whenever you are displaying anything on the screen whether it is text or graphics (2D or 3D).

    http://www.benryves.com/tutorials/?t=winconsole

    0 讨论(0)
  • 2020-12-09 11:49

    Joseph, JP, and CodingTheWheel all provided valuable help.

    For my simple case, the most straight-forward approach seemed to be based on CodingTheWheel's answer:

    // before entering update loop
    HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
    GetConsoleScreenBufferInfo(h, &bufferInfo);
    
    // update loop
    while (updating)
    {
      // reset the cursor position to where it was each time
      SetConsoleCursorPosition(h, bufferInfo.dwCursorPosition);
    
      //...
      // insert combinations of sprintf, printf, etc. here
      //...
    }
    

    For more complicated problems, the full console API as provided by JP's answer, in coordination with the examples provided via the link from Joseph's answer may prove useful, but I found the work necessary to use CHAR_INFO too tedious for such a simple app.

    0 讨论(0)
  • 2020-12-09 11:49

    In case the Joseph's suggestion does not give you enough flexibility, have a look at the Console API: http://msdn.microsoft.com/en-us/library/ms682073(VS.85).aspx.

    0 讨论(0)
  • 2020-12-09 12:03

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

    0 讨论(0)
  • 2020-12-09 12:06

    In Linux, you can accomplish this by printing \b and/or \r to stderr. You might need to experiment to find the right combination of things in Windows.

    0 讨论(0)
提交回复
热议问题