赞
踩
windows API之控制台界面
tkorays (tkorays@hotmail.com)
- #include <stdio.h>
- #include <Windows.h>
-
- int main(int argc, char** argv){
- HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE); // 获取输出句柄
- HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE); // 获取输入句柄
-
- CONSOLE_SCREEN_BUFFER_INFO backInfo;
- GetConsoleScreenBufferInfo(hStdout, &backInfo); // 保存原始信息
-
- DWORD dwSize;
-
- // 设置颜色
- WriteConsoleA(hStdout, "I'm tkorays.\n", 13, &dwSize, NULL); // 未设置字体颜色,内容为ASCII编码
- SetConsoleTextAttribute(hStdout, FOREGROUND_RED | FOREGROUND_INTENSITY);
- WriteConsole(hStdout, L"hello\n", 6, &dwSize, NULL); // 设置颜色后输出,UNICODE编码
- SetConsoleTextAttribute(hStdout, FOREGROUND_GREEN | FOREGROUND_INTENSITY);
- system("pause"); // 暂停下,看前面的效果
-
-
- LPWSTR lpChar = (LPWSTR)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, 2048);
- COORD coord; // 相对坐标
- coord.X = 0;
- coord.Y = 0;
- CONSOLE_SCREEN_BUFFER_INFO csbi;
- GetConsoleScreenBufferInfo(hStdout, &csbi); // 获取此时屏幕缓存
- ReadConsoleOutputCharacter(hStdout, lpChar, 2047, coord, &dwSize); // 获取屏幕缓存
-
- // 颜色数组,用于后面设置
- WORD wColors[3];
- wColors[0] = BACKGROUND_BLUE | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN;
- wColors[1] = BACKGROUND_RED | BACKGROUND_GREEN;
- wColors[2] = BACKGROUND_GREEN;
-
- // 修改屏幕缓存
- DWORD dwLen;
- for (size_t i = 0; i < dwSize; i++){
- // 屏幕中的小写字母改变样式
- if (lpChar[i] >= 'a'&&lpChar[i] <= 'z'){
- // 计算字符坐标
- coord.Y = i / csbi.dwSize.X;
- coord.X = i%csbi.dwSize.X;
- WriteConsoleOutputAttribute(hStdout, wColors, 1, coord, &dwLen);
- }
- }
-
- // 恢复原始字体颜色
- SetConsoleTextAttribute(hStdout, backInfo.wAttributes);
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。