屏幕上输出变量
以下代码粘贴后可以直接使用
注意:记得先包含头文件#include <sstream>
/**************************************************************************** 在屏幕上输出变量。 1.需要包含头文件。#include <sstream> 。并且放在放在文件前头 2.函数 DrawTextOnScreen只能输入字符串 3.函数 OutputString可以自动适应参数类型,如int short double 4.程序退出时调用析构函数刷新整个屏幕 5.支持Unicode 6.更好的方法请看: http://blog.youkuaiyun.com/jacky_qiu/archive/2010/11/04/5986089.aspx ****************************************************************************/ void DrawTextOnScreen(const TCHAR* OutputStr) { //━━━━━━━━程序关闭时析构函数调用InvalidateRect刷新屏幕━━━━ class CClearScreen {public: ~CClearScreen() { ::InvalidateRect(NULL,NULL,false);} }; static CClearScreen temp; //━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ //━━━━━━━━━━━━━━━━━━━━━━━━获取OutputStr的行数━━━━━━━━ const TCHAR* p=OutputStr; int RowCount=1; for(;*p;p++) {if (*p=='/r') RowCount++; } //━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ static int DrawRectTop=0; //DrawRectBottom输出字符串的矩形区域底边,16*RowCount为高度 int DrawRectBottom=DrawRectTop+16*RowCount; //超过屏幕从新归0 if (DrawRectBottom>=GetSystemMetrics(SM_CYSCREEN)) { DrawRectTop=0; DrawRectBottom=16*RowCount; } HDC hdc=::GetDC(NULL); //输出字符串的矩形区域 RECT rect={0,DrawRectTop,300,DrawRectBottom}; //填充黑色矩形 ::FillRect(hdc,&rect,(HBRUSH)GetStockObject(BLACK_BRUSH)); //输出文本 SetTextColor(hdc,RGB(255,255,255)); SetBkColor(hdc,RGB(0,0,0)); ::DrawText (hdc,OutputStr,-1,&rect,DT_EDITCONTROL|DT_EXPANDTABS|DT_LEFT |DT_NOCLIP ) ; //修改DrawRectTop为下次做准备 DrawRectTop=DrawRectBottom; //画最后的结束提示字符串 rect.top=DrawRectTop; rect.bottom=rect.top+16; SetBkColor(hdc,RGB(0,255,0)); ::DrawText (hdc,_T("━━━━━━━━━━━━━━━━━━━━━━━━━"),-1,&rect,DT_EXPANDTABS|DT_LEFT) ; ::ReleaseDC(NULL,hdc); } /**************************************************************************** 常用数据类型转换成字符串 ****************************************************************************/ template <class T> void OutputString(T val) { #ifdef _UNICODE std::wostringstream FormatString; FormatString<<val; std::wstring tempstr(FormatString.str()); const TCHAR* OutputStr=tempstr.c_str(); #else std::ostringstream FormatString; FormatString<<val; std::string tempstr(FormatString.str()); const TCHAR* OutputStr=tempstr.c_str(); #endif DrawTextOnScreen(OutputStr); } |
调用示例:
void CDemoDlg::OnButton1() { TCHAR buf[100]=_T("Impossible is nothing"); TCHAR buf2[100]=_T("this is multi line/r/nfirst line/r/nsecond line"); int a=45; double b=67.45; double c=847.424;short d=324; bool e=true; OutputString(_T("Impossible is nothing")); OutputString(buf); OutputString(buf2); OutputString(a); OutputString(b); OutputString(c); OutputString(e); } |