공부/C++
[C++] 콘솔창 키입력 메뉴이동 ConsoleHandle
래울
2023. 7. 19. 17:06
- 코드
#include <iostream>
#include <conio.h>
#include <Windows.h>
//#include "KeyClass.h"
enum KeyList
{
UP = 72,
LEFT = 75,
RIGHT = 77,
DOWN = 80,
};
#define MENU_LENGTH 5
using namespace std;
void Init();
void SetConsoleCursorPosition(int x, int y);
void InputKey();
COORD GetConsoleCursorPosition();
void PrintMainPage();
void MoveMenuCursorUP();
void MoveMenuCursorDOWN();
int main()
{
Init();
while (true)
{
InputKey();
}
return 0;
}
void Init()
{
_wsetlocale(LC_ALL, L"korean");
system("mode con cols=64 lines=24 | title test");
PrintMainPage();
SetConsoleCursorPosition(27, 2);
}
void SetConsoleCursorPosition(int x, int y)
{
HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(consoleHandle, pos);
}
COORD GetConsoleCursorPosition()
{
CONSOLE_SCREEN_BUFFER_INFO cs;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cs);
return cs.dwCursorPosition;
}
void PrintMainPage()
{
wcout << L"메인화면" << endl;
SetConsoleCursorPosition(26, 2);
wcout << L"> 테스트" << 1 << endl;
for (int i = 1; i < MENU_LENGTH; ++i) {
SetConsoleCursorPosition(28, i + 2);
wcout << L"테스트" << i+1 << endl;
}
}
void MoveMenuCursorUP()
{
COORD pos = GetConsoleCursorPosition();
if (pos.Y <= 2) {
}
else{
SetConsoleCursorPosition(26, pos.Y);
cout << " ";
SetConsoleCursorPosition(26, pos.Y - 1);
cout << ">";
}
}
void MoveMenuCursorDOWN()
{
COORD pos = GetConsoleCursorPosition();
if (pos.Y >= 1+MENU_LENGTH) {
}
else {
SetConsoleCursorPosition(26, pos.Y);
cout << " ";
SetConsoleCursorPosition(26, pos.Y + 1);
cout << ">";
}
}
void InputKey()
{
int key = 0;
if (_kbhit() > 0)
{
key = _getch();
// 방향키 입력
if(key == 224)
{
//up:72, left:75, right:77, down:80
key = _getch();
switch (key)
{
case KeyList::UP:
MoveMenuCursorUP();
break;
case KeyList::LEFT:
break;
case KeyList::RIGHT:
break;
case KeyList::DOWN:
MoveMenuCursorDOWN();
break;
default:
break;
}
}
}
}