반응형

win32 console API

 

GetConsoleWindow                  //콘솔 윈도우 윈도우핸들 얻기
GetConsoleMode                     //현재 콘솔의 입출력 모드 얻기
SetConsoleMode                     //콘솔의 입출력 모드 설정
GetConsoleCursorPosition        //스크린 버퍼의 커서 위치 변경
GetConsoleCursorInfo              //스크린 버퍼의 커서 정보 얻기
SetConsoleCursorInfo              //스크린 버퍼의 커서 정보 설정
SetConsoleWindowInfo             //콘솔 윈도우의 정보 설정
CreatConsoleScreenBuffer        //스크린 버퍼 생성
GetConsoleScreenBufferInfo      //스크린 버퍼 정보 얻기
SetConsoleScreenBufferSize     //스크린 버퍼 크기 변경
SetConsoleTextAttribute            //기본 문자 속성 설정, 고수준 출력함수에서 사용
ScrollConsoleScreenBuffer        //스크린 버퍼의 내용 스크롤
SetConsoleActiveScreenBuffer   //활성 스크린 버퍼 변경
GetCurrentConsoleFont             //콘솔에서 사용중인 폰트 정보 얻기

 

COORD 구조체

콘솔에서 좌표를 나타내기위한 구조체

 

typedef struct _COORD { // coord.
    SHORT X;      // horizontal coordinate
    SHORT Y;      // vertical coordinate
} COORD;

 

// 커서의 좌표를 조사한다.
COORD getCursorPosition(void)
{
    CONSOLE_SCREEN_BUFFER_INFO buffInfo;

    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE),&buffInfo); //현재콘솔스크린버퍼에서 정보읽어와서

                                                                                                                  //buffInfo에 저장
    return   buffInfo.dwCursorPosition; //CONSOLE_SCREEN_BUFFER_INFO구조체형변수 buffInfo에 속한 멤버변수이고
}                                                   //COORD형인  dwCursorPosition을 리턴   (x,y좌표값이 들어있다)

//나중에 사용할 코딩부분 //////////////////
//콘솔의 스크린 버퍼사이즈 변경할 소스코드
COORD bufferSize = {80, 25};
SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), bufferSize);
//////////////////////////////////////////////////////////////////////////////////////////



http://kin.naver.com/qna/detail.nhn?d1id=1&dirId=1040101&docId=72177697&qb=U2V0Q29uc29sZVNjcmVlbkJ1ZmZlclNpemU=&enc=utf8&section=kin&rank=2&sort=0&spq=0&pid=fINGjv331xwsssyZ6jZssv--057430&sid=S6b8EfbepksAAH9dHjI

http://www.adrianxw.dk/SoftwareSite/Consoles/Consoles6.html

http://msdn.microsoft.com/en-us/library/ms683231(VS.85).aspx <==GetStdHandle Function

Value Meaning
STD_INPUT_HANDLE
(DWORD)-10

The standard input device. Initially, this is the console input buffer, CONIN$.

STD_OUTPUT_HANDLE
(DWORD)-11

The standard output device. Initially, this is the active console screen buffer, CONOUT$.

STD_ERROR_HANDLE
(DWORD)-12

The standard error device. Initially, this is the active console screen buffer, CONOUT$.


STD_OUTPUT_HANDLE 활성화된 콘솔 스크린에 핸들을 가져오는 건가?? 

A console process uses handles to access the input and screen buffers of its console. A process can use the GetStdHandle, CreateFile, or CreateConsoleScreenBuffer function to open one of these handles.

The GetStdHandle function provides a mechanism for retrieving the standard input (STDIN), standard output (STDOUT), and standard error (STDERR) handles associated with a process. During console creation, the system creates these handles. Initially, STDIN is a handle to the console's input buffer, and STDOUT and STDERR are handles of the console's active screen buffer. However, the SetStdHandle function can redirect the standard handles by changing the handle associated with STDIN, STDOUT, or STDERR. Because the parent's standard handles are inherited by any child process, subsequent calls to GetStdHandle return the redirected handle. A handle returned by GetStdHandle may, therefore, refer to something other than console I/O. For example, before creating a child process, a parent process can use SetStdHandle to set a pipe handle to be the STDIN handle that is inherited by the child process. When the child process calls GetStdHandle, it gets the pipe handle. This means that the parent process can control the standard handles of the child process. The handles returned by GetStdHandle have GENERIC_READ | GENERIC_WRITE access unless SetStdHandle has been used to set the standard handle to have lesser access.

The value of the handles returned by GetStdHandle are not 0, 1, and 2, so the standard predefined stream constants in Stdio.h (STDIN, STDOUT, and STDERR) cannot be used in functions that require a console handle.

The CreateFile function enables a process to get a handle to its console's input buffer and active screen buffer, even if STDIN and STDOUT have been redirected. To open a handle to a console's input buffer, specify the CONIN$ value in a call to CreateFile. Specify the CONOUT$ value in a call to CreateFile to open a handle to a console's active screen buffer. CreateFile enables you to specify the read/write access of the handle that it returns.

The CreateConsoleScreenBuffer function creates a new screen buffer and returns a handle. This handle can be used in any function that accepts a handle to console output. The new screen buffer is not active until its handle is specified in a call to the SetConsoleActiveScreenBuffer function. Note that changing the active screen buffer does not affect the handle returned by GetStdHandle. Similarly, using SetStdHandle to change the STDOUT handle does not affect the active screen buffer.

Console handles returned by CreateFile and CreateConsoleScreenBuffer can be used in any of the console functions that require a handle to a console's input buffer or of a console screen buffer. Handles returned by GetStdHandle can be used by the console functions if they have not been redirected to refer to something other than console I/O. If a standard handle has been redirected to refer to a file or a pipe, however, the handle can only be used by the ReadFile and WriteFile functions.

A process can use the DuplicateHandle function to create a duplicate console handle that has different access or inheritability from the original handle. Note, however, that a process can create a duplicate console handle only for its own use. This differs from other handle types (such as file, pipe, or mutex objects), for which DuplicateHandle can create a duplicate that is valid for a different process.

To close a console handle, a process can use the CloseHandle function.


콘솔 생성

BOOL AllocConsole(VOID);
콘솔창을 생성한다. 실패하면 FALSE을 반환한다.

BOOL FreeConsole(VOID);
열려진 콘솔을 닫는다.

HANDLE GetStdHandle(DWORD nStdHandle);
콘솔의 표준 핸들을 구하는 함수이다.
인자로 STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE 중 하나를 넣어준다.

콘솔 정보 구하기

BOOL GetConsoleSc0reenBufferInfo(
HANDLE hConsoleOuput, // 콘솔의 핸들
PCONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo // 콘솔의 정보와 관련된 구조체
);
콘솔의 커서의 위치와 콘솔의 정보를 조사한다.

typedef struct _CONSOLE_SCREEN_BUFFER_INFO {
COORD dwSize; // 화면 버퍼의 크기. 크기는 셀 단위이다.
COORD dwCursorPosition; // 커서의 현재 위치
WORD wAttributes; // 출력될 문자의 전경색과 배경색의 정보
SMALL_RECT srWindow; // 현재 보이는 화면 영역에 대한 좌표
COORD dwMaximumWindowSize; // 최대 화면의 크기 모니터의 해상도와 시스템 글꼴에 따라 달라진다.
} CONSOLE_SCREEN_BUFFER_INFO ;

전경, 배경 컬러
#define FOREGROUND_BLUE 0x0001
#define FOREGROUND_GREEN 0x0002
#define FOREGROUND_RED 0x0004
#define FOREGROUND_INTENSITY 0x0008
#define BACKGROUND_BLUE 0x0010
#define BACKGROUND_GREEN 0x0020
#define BACKGROUND_RED 0x0040
#define BACKGROUND_INTENSITY 0x0080

typedef struct _COORD {
SHORT X;
SHORT Y;
} COORD;

typedef struct _SMALL_RECT {
SHORT Left;
SHORT Top;
SHORT Right;
SHORT Bottom;
} SMALL_RECT;

BOOL SetConsoleCursorPosition(
HANDLE hConsoleOutput, // 콘솔의 핸들
COORD dwCursorPosition // 커서의 위치
);
콘솔의 커서의 위치를 설정한다.

BOOL SetConsoleCursorInfo(
HANDLE hConsoleOutput, // 콘솔 핸들
CONST CONSOLE_CURSOR_INFO *lpConsoleCursorInfo // 커서 모양의 구조체
);
커서의 크기를 구조체의 정보에 의해 바꾼다.

typedef struct _CONSOLE_CURSOR_INFO {
DWORD dwSize; // 100분율의 크기
BOOL bVisible; // FALSE 로 하면 보이지 않음
} CONSOLE_CURSOR_INFO, *PCONSOLE_CURSOR_INFO;

BOOL GetConsoleCursorInfo(
HANDLE hConsoleOutput, // 콘솔 핸들
PCONSOLE_CURSOR_INFO lpConsoleCursorInfo // 커서 정보
);
위의 함수에 상응하는 커서 정보를 알아오는 함수이다.

BOOL SetConsoleMode(
HANDLE hConsoleHandle, // 콘솔 핸들
DWORD dwMode // 모드
);
콜솔 모드를 선택한다.
밑의 모드들은 OR연산으로 중복 선택이 가능하다.

dwMode
ENABLE_PROCESSED_INPUT
편집키와 제어키를 문자 입력으로 받지 않고 해당 키의 기능을 처리하도록 한다.
BackSpace, Enter등의 제어키들의 기능을 수행한다.

ENABLE_LINE_INPUT
ReadFile, ReadConsole등의 함수로 문자열을 받을 때 Enter키가 눌러질 때 까지 입력을 받는다.
이 모드가 설정되어 있지 않으면 입력 버퍼에 한글자라도 있으면 바로 리턴한다.

ENABLE_ECHO_INPUT
입력중인 문자열을 화면으로 다시 보여주어 사용자가 확인할 수 있도록 해 준다.
이 모드가 설정되어 있지 않으면 입력중인 문자열을 사용자가 볼 수 없다.

ENABLE_MOUSE_INPUT
마우스의 커서의 위치, 변화, 클릭, 더블클릭등의 상태를 조사할 수 있다.

ENABLE_WINDOW_INPUT
콘솔창의 등록 정보창에서 화면 버퍼의 크기를 변경할 경우 버퍼 크기 변경 이벤트를 입력 버퍼에 넣는다. 버퍼의 크기에 따라 화면을
재구성해야 한다면 이 이벤틀를 받아서 처리한다.
나머지 다섯가지 입력 모드중 이 모드만 디폴트로 제외 되어 있다.

ENABLE_PROCESSED_OUTPUT
출력시 제어코드를 문자로 출력하지 않고 기능으로 출력한다.

ENABLE_WRAP_AT_EOL_OUTPUT
행의 끝 부분에 문자가 출력될때 다음줄로 자동으로 개행된다. 화면의 제일 아래쪽으로 출력되고자 할때 화면을 스크롤 한다.

BOOL GetConsoleMode(
HANDLE hConsoleHandle, // 콘솔 핸들
LPDWORD lpMode // 모드
);
현재의 콘솔의 모드를 반환한다.

BOOL SetConsoleCtrlHandler(
PHANDLER_ROUTINE HandlerRoutine, // 함수 포인터
BOOL Add // TRUE이면 이 핸들러가 추가되고, FALSE 이면 제거 된다.
);
콘솔의 핸들러를 지정한다.

핸들러의 원형은 밑의 형식이다.
BOOL WINAPI HandlerRoutine(DWORD dwCtrlType);
여기서 넘어오는 dwCtrlType은 이 핸들러 함수를 호출한 신호 유형을 알려준다.
여기서 반환되는 값이 TRUE이면 나머지 등록되어 있는 핸들러는 실행 되지 않는다.
FALSE를 반환할때는 다음 핸들러로 제어를 넘긴다.
dwCtrlType
CTRL_C_EVENT Ctrl+C 가 입력되었음
CTRL_BREAK_EVENT Ctrl+Break가 입력되었음
CTRL_CLOSE_EVENT 콘솔창이 닫힐 때 이 콘솔에 연결된 모든 프로세스에게 보내진다.
CTRL_LOGOFF_EVENT 사용자가 로그오프할 때 보내진다.
CTRL_SHUTDOWN_EVENT 시스템이 셧다운될 때 보내진다.

HANDLE CreateConsoleScreenBuffer(
DWORD dwDesiredAccess, // 버퍼의 읽기, 쓰기모드에 대한 내용 ( GENERIC_READ, GENERIC_WRITE등의 플래그 조합 )
DWORD dwShareMode, // 콘솔의 공유 모드. 공유하지 않을때는 0.
CONST LPSECURITY_ATTRIBUTES lpSecurityAttributes, // 보안 설명자. 그냥 NULL.
DWORD dwFlags, // 콘솔의 타입인데 현재 가능한 값은 CONSOLE_TEXTMODE_BUFFER 만 있음.
LPVOID lpScreenBufferData // 예약 값. 무조건 NULL.
);
복수개의 화면을 생성한다. 콘솔의 입력 버퍼는 하나만 존재하지만 출력 버퍼는 여러개가 존재 할수 있다.

BOOL SetConsoleActiveScreenBuffer(HANDLE hConsoleOutput);
화면 출력 버퍼를 선택한다.


콘솔에 쓰기

DWORD WriteConsole(
HANDLE hConsoleOutput, // 콘솔 핸들
CONST VOID *lpBuffer, // 버퍼
DWORD nNumberOfCharsToWrite, // 쓰여질 문자열의 길이
LPDWORD lpNumberOfCharsWritten, // 쓰여진 문자열의 길이
LPVOID lpResserved // 예약된 변수
);
ANSI문자열이나 UNICODE문자열을 출력할수 있다. WriteFile함수로도 콘솔 핸들로 출력할수 있으니 ANSI파일밖에 출력 할 있다.

BOOL WriteConsoleOutput(
HANDLE hConsoleOutput, // 콘솔 핸들
CONST CHAR_INFO *lpBuffer, // 버퍼
COORD dwBufferSize, // 버퍼의 크기 (X,Y의 좌표로 행과 열을 뜻한다.)
COORD dwBufferCoord, // 버퍼내의 출력 대상 셀의 좌표를 지정한다.
PSMALL_RECT lpWriteRegion // 화면의 출력할 좌표
);
문자와 색상의 속성으로 콘솔에 출력한다.

typedef struct _CHAR_INFO {
union {
WCHAR UnicodeChar;
CHAR AsciiChar;
} Char;
WORD Attributes;
} CHAR_INFO, *PCHAR_INFO;

BOOL WriteConsoleOutputCharacter(
HANDLE hConsole hConsoleOutput, // 콘솔 핸들
LPCTSTR lpCharacter, // 문자열
DWORD nLength, // 길이
COORD dwWriteCoord, // 위치
LPDWORD lpNumberOfCharsWritten // 쓰여진 문자열의 길이
);
위치에 문자를 출력한다.

BOOL WriteConsoleOutputAttribute(
HANDLE hConsoleOutput, // 콘솔 핸들
CONST WORD *lpAttribute, // 속성
DWORD nLength, // 길이
COORD dwWriteCoord, // 위치
LPDWORD lpNumberOfAttrsWritten // 쓰여진 속성의 크기
);
위치의 속성을 변경한다.

콘솔에서 읽기

BOOL ReadConsole(
HANDLE hConsoleInput, // 콘솔핸들
LPVOID lpBuffer, // 버퍼
DWORD nNumberOfCharsToRead, // 읽을 문자열의 길이
LPDWORD lpNumberOfCharsRead, // 읽어진 변수
LPVOID lpReserved // 예약된 변수
);
ANSI문자열이나 UNICODE문자열을 읽을 수 있다.

출력 3함수에 대응하는
ReadConsoleOutput
ReadConsoleOutputCharacter
ReadConsoleOutputAttribute

//콘솔 어태치?


//어태치  사용




+ Recent posts