WriteConsoleOutputCharacter

函式簡介,程式示例,

函式簡介

函式原型:
BOOL WriteConsoleOutputCharacter( // 在指定位置處插入指定數量的字元
HANDLE hConsoleOutput, // 句柄
LPCTSTR lpCharacter, // 字元串
DWORD nLength, // 字元個數
COORD dwWriteCoord, // 起始位置
LPDWORD lpNumberOfCharsWritten // 已寫個數
);
參數簡介:
hConsoleOutput:控制台輸出句柄,通過調用GetStdHandle函式獲得
HANDLE hnd;
hnd=GetStdHandle(STD_INPUT_HANDLE);
lpCharacter:要輸出的字元串
nLength:輸出長度
dwWriteCoord:起始位置
其中,COORD是個結構體變數類型
typedef struct _COORD {
SHORT X;
SHORT Y;
} COORD;
lpNumberOfCharsWritten:已寫個數,通常置為NULL

程式示例

示例一:
#include <windows.h>
#include <string.h>
int main(void)
{
COORD size = {10, 10};
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
WriteConsoleOutputCharacter(hOut,"Hello,World",strlen("Hello,World"),size,NULL);
return 0;
}
示例二:
// 在DOS視窗中央輸出“Hello,World”
#include <windows.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
COORD size;
int length;
CONSOLE_SCREEN_BUFFER_INFO bInfo; // 視窗緩衝區信息
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo( hOut, &bInfo ); // 獲取視窗緩衝區信息
char *strText = "Hello,World!";
length = strlen(strText);
size.X = ( bInfo.dwSize.X - length ) / 2;
size.Y = bInfo.dwSize.Y / 2;
WriteConsoleOutputCharacter(hOut,strText,length,size,NULL);
return 0;
}
示例三:
#include<iostream>
#include<iomanip>
#include<windows.h>
using namespace std;
void Draw(HANDLE hand,int colour,char *s,int len,COORD point,LPDWORD lPdword);
int main()
{
int x=4;
int y=4;
HANDLE hand;
hand=GetStdHandle(STD_OUTPUT_HANDLE);
int colour=200;
int len=2;
COORD point = {x,y};
SMALL_RECT rt = {0,0,35,32}; // 視窗尺寸
SetConsoleWindowInfo(hand,true,&rt); // 由於DOS默認只有25行,為了便於觀察,把dos視窗行數調為35,這個也可以用system函式實現
char *string="■";
Draw(hand,colour,string,len,point,NULL);
INPUT_RECORD keyRec;
DWORD res;
HANDLE hnd;
hnd=GetStdHandle(STD_INPUT_HANDLE);
for(;;)
{
cout<<setfill('0')<<"("<<setw(2)<<point.X<<","<<setw(2)<<point.Y<<")";
ReadConsoleInput(hnd,&keyRec,1,&res);
if(keyRec.EventType==KEY_EVENT)
{
if(keyRec.Event.KeyEvent.wVirtualKeyCode==65)
{
if(point.X>1) // 這裡不用那么麻煩,因為按a時只會使X減小,下同
{
Draw(hand,1," ",len,point,NULL);
point.X-=1;
Draw(hand,colour,string,len,point,NULL);
}
}
if(keyRec.Event.KeyEvent.wVirtualKeyCode==68)
{
if(point.X<30)
{
Draw(hand,1," ",len,point,NULL);
point.X+=1;
Draw(hand,colour,string,len,point,NULL);
}
}
if(keyRec.Event.KeyEvent.wVirtualKeyCode==87)
{
if(point.Y>1)
{
Draw(hand,1," ",len,point,NULL);
point.Y-=1;
Draw(hand,colour,string,len,point,NULL);
}
}
if(keyRec.Event.KeyEvent.wVirtualKeyCode==83)
{
if(point.Y<30)
{
Draw(hand,1," ",len,point,NULL);
point.Y+=1;
Draw(hand,colour,string,len,point,NULL);
}
}
}
cout<<"\b\b\b\b\b\b\b";
}
}
void Draw(HANDLE hand,int colour,char *s,int len,COORD point,LPDWORD lPdword)
{
FillConsoleOutputAttribute(hand,colour,len,point,lPdword);
WriteConsoleOutputCharacter(hand,s,len,point,lPdword);
}

相關詞條

熱門詞條

聯絡我們