代码改变世界

调用API 清屏

2016-04-22 15:10  Dorisoy  阅读(480)  评论(0编辑  收藏  举报
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;

namespace calculate
{
    struct StdHandleEnum
    {
        public const int STD_INPUT_HANDLE = -10;
        public const int STD_OUTPUT_HANDLE = -11;
        public const int STD_ERROR_HANDLE = -12;
    };

    static class ConsoleEx
    {
        internal struct COORD
        {
            public short X;
            public short Y;
        }

        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        internal struct CONSOLE_SCREEN_BUFFER_INFO
        {
            public COORD Size;
            public COORD p1;
            public short a1;
            public short w1;
            public short w2;
            public short w3;
            public short w4;
            public COORD m1;
        }

        [DllImport("kernel32.dll")]
        public static extern int GetStdHandle(int nStdHandle);

        [DllImport("kernel32.dll")]
        public static extern bool GetConsoleScreenBufferInfo(int hConsoleOutput, out CONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo);

        [DllImport("kernel32.dll")]
        public static extern bool SetConsoleCursorPosition(int hConsoleOutput, COORD dwCursorPosition);

        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern bool FillConsoleOutputCharacter(int hConsoleOutput, short cCharacter, int nLength, COORD WriteCoord, out int lpNumberOfCharsWritten);

        public static void Clear()
        {
            CONSOLE_SCREEN_BUFFER_INFO CSBI;
            int hOut;
            int CharOut;
            COORD Home;

            hOut = GetStdHandle(StdHandleEnum.STD_OUTPUT_HANDLE);

            GetConsoleScreenBufferInfo(hOut, out CSBI);

            Home.X = 0;
            Home.Y = 0;

            FillConsoleOutputCharacter(hOut, (short)' ', CSBI.Size.X * CSBI.Size.Y, Home, out CharOut);

            SetConsoleCursorPosition(hOut, Home);
        }
    }
}