C++ 设置控制台文本属性画一个DOS时代的字符窗口

<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;
}

执行结果如下:

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hann Yang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值