Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the console buffer without the last line with C#?

Tags:

c#

What I'm trying to achieve is a self-compiled c# file without toxic output.I'm trying to achieve this with Console.MoveBufferArea method but looks does not work. Eg. - save the code below with .bat extension :

// 2>nul||@goto :batch
/*
:batch
@echo off
setlocal

:: find csc.exe
set "frm=%SystemRoot%\Microsoft.NET\Framework\"
for /f "tokens=* delims=" %%v in ('dir /b /a:d  /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do (
   set netver=%%v
   goto :break_loop
)
:break_loop
set csc=%frm%%netver%\csc.exe
:: csc.exe found
%csc% /nologo /out:"%~n0.exe" "%~dpsfnx0" 
%~n0.exe
endlocal
exit /b 0
*/
public class Hello
{
   public static void Main() {
      ClearC();
      System.Console.WriteLine("Hello, C# World!");
   }

   private static void ClearC() {
        System.Console.MoveBufferArea(
            0,0,
            System.Console.BufferWidth,System.Console.BufferHeight-1,
            0,0
        );
   }
}

the output will be:

C:\>//  2>nul  ||
Hello, C# World!

What want is to rid of the // 2>nul || .Is it possible? Is there something wrong in my logic (the ClearC method)?Do I need PInvoke?

like image 399
npocmaka Avatar asked Jun 19 '15 22:06

npocmaka


1 Answers

If you want to do it in the C#, then changing your ClearC function to the following seems to work:

public static void ClearC() {
    System.Console.CursorTop = System.Console.CursorTop - 1;
    System.Console.Write(new string(' ', System.Console.BufferWidth));
    System.Console.CursorTop = System.Console.CursorTop - 1;
}

Essentially, move the Cursor up a line (to the line that should contain your prompt), blank the entire line, then move up another line (which should move you to the blank line between commands). Future output will then take place from here.

The obvious downside to this is that you need to wait for the C# code to be compiled and executed, before the // 2>nul || is removed. If you want it to be faster, you'll need to find a console/batch file based solution. The other thing to keep in mind is that is assumes that the prompt is a single line. If it's a really long prompt that spans two lines, then you'll get a bit of a mess, so it may be better to clear two lines, depending on how you're planning on using this.

If you want to go the whole hog and start reading the console buffer to determine how long the prompt is, then you might want to have a look at this question. Whilst the article link in the answer is broken, the code download still seems to work.

If you want to go down the batchfile based approach, then you might want to have a look at this question.

like image 67
forsvarir Avatar answered Nov 11 '22 20:11

forsvarir