C++ 设置控制台文本属性画一个DOS时代的字符窗口
2023-09-14 09:01:28 时间
<windows.h>库函数:SetConsoleCursorPosition() 设置控制台光标位置;SetConsoleTextAttribute() 设置控制台文本属性,主要用它来设置颜色。用这两个函数在控制台屏幕上画2个在DOS时代可算得上比较洋气的字符窗口 ^_^
#include <iostream>
#include <windows.h>
using namespace std;
struct winRect {
LONG left=0;
LONG top=0;
LONG width=30;
LONG height=3;
SHORT foreColor=14;
SHORT bgColor=1;
string sTitle="";
};
void gotoXY(short x, short y)
{ //设置光标位置,坐标从左上角(0,0)起始
COORD position = {x, y};
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(hConsole, position);
}
void setColor(unsigned short foreColor=7,unsigned short bgColor=0)
{ //设置输出文本的前景色和背景色
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
foreColor%=16; bgColor%=16;
SetConsoleTextAttribute(hConsole,foreColor|bgColor*16);
}
string rept(string s, int i)
{
string t="";
for(int j=0;j<i;j++) t+=s;
return t;
}
int paintWin(winRect w)
{
int top,bottom,x=w.left,y=w.top;
bool bT=(w.sTitle!="");
bottom=w.top+w.height;
setColor(w.foreColor,w.bgColor);
string a="━",b=" ";
w.height=w.height>2?w.height:3;
w.height=bT?w.height+2:w.height;
w.width=w.width>5?w.width:6;
w.width=w.width%2==1?w.width+1:w.width;
top=y;
gotoXY(x,y++);
cout<<"┏"<<rept(a,w.width/2-2)<<"┓";
for (int i=0;i<w.height-2;i++){
gotoXY(x,y++);
cout<<"┃"<<rept(b,w.width-4)<<"┃";
}
gotoXY(x,y++);
cout<<"┗"<<rept(a,w.width/2-2)<<"┛";
bottom=y;
gotoXY(x+2,top+1);
if (bT) {
gotoXY(x,w.top+2);
cout<<"┣"<<rept(a,w.width/2-2)<<"┫";
gotoXY(x+2,w.top+1);
cout<<w.sTitle.substr(0,w.width-4);
gotoXY(x+2,top+3);
}
return bottom;
}
int main(void)
{
int ymax;
char s[20];
char t[]="字符窗口测试";
SetConsoleTitle(t);
winRect w;
w.bgColor = 3;
w.foreColor = 11;
w.width = 20;
w.height = 6;
ymax=paintWin(w);
cout<<"hello, window!";
winRect win;
win.left = 24;
win.top = 10;
win.sTitle = "标题:123456789012345678901234567890"; //如标题太长,随窗口宽度截短
ymax=paintWin(win);
cout<<"abcdefghijklmnopqrstuvwxyz"; //正文长度未作处理,要注意不能超过 窗口宽度-4
setColor();
gotoXY(0,ymax);
return 0;
}
执行结果如下:
相关文章
- C++Qt入门(1)—Qt简介,第一个Qt程序,Qt按钮
- C++并发编程 - 同步并发操作
- c++获取子类窗口句柄位置_C++中各种获取窗口句柄的方法「建议收藏」
- C++学生选课系统 【含 代码】
- 链表排序总结(全)(C++)[通俗易懂]
- c++中constexpr_define和const定义常量的区别
- c++int转换成char_字符数字转为int型
- c++禁止隐式转换_无法将int隐式转换为类
- C++字符串加密_c++字符串连接函数
- c++的链表-C++实现简单链表
- C/C++ 目录递归与结束递归
- 从C和C++内存管理来谈谈JVM的垃圾回收算法设计-下
- C++11 Lambda表达式
- Sunday 字符串匹配算法(C++实现)详解编程语言
- C++11多线程编程详解
- C++ search(STL search)算法详解
- C++ string支持迭代器方法详解
- cin.ignore():C++跳过(忽略)指定字符
- C++多字节字符与宽字节字符相互转换
- C/C++中如何判断某一文件或目录是否存在
- C++中给二维指针分配内存(实现代码)
- c++支持coroutine的简单示例
- C++基础入门教程(八):函数指针
- C++中可正确获取UTF-8字符长度的函数分享
- VC++中HTControl的CHTButton按钮控件类用法实例解析
- C++实现二维图形的傅里叶变换