<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;
}
执行结果如下: