The Windows threads operation and console C program example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows Xp Pro SP2

Target platform: none, just for learning and fun

Header file: Standard and Windows

Additional library: Windows Platform SDK

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info: non-CLR or unmanaged.

To do: The Windows threads operation and console C code sample

To show: Demonstrate the use of Windows thread and process Win32 functions

 

 

 

/* CRT thread */

#include <windows.h>

#include <stdio.h>

 

CONSOLE_SCREEN_BUFFER_INFO csbi;

 

int main(void)

{

HANDLE hStdOut;

DWORD cWritten;

BOOL fSuccess;

COORD coord;

WORD wColor;

CHAR chFillChar;

 

hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);

 

if (hStdOut == INVALID_HANDLE_VALUE)

printf("GetStdHandle() failed, error: %d.\n", GetLastError());

else

printf("GetStdHandle() is OK.\n");

 

/* Get display screen's text row and column information. */

if (GetConsoleScreenBufferInfo(hStdOut, &csbi) == 0)

printf("GetConsoleScreenBufferInfo() failed, error: %d.\n", GetLastError());

else

printf("GetConsoleScreenBufferInfo() is OK.\n");

 

// Fill a 30-by-20-character screen buffer with the space character.

coord.X = 0; // start at 0th cell

coord.Y = 6; // of sixth row

chFillChar = ' ';

 

fSuccess = FillConsoleOutputCharacter(

hStdOut, // screen buffer handle

chFillChar, // fill with spaces

30*20, // number of cells to fill

coord, // first cell to write to

&cWritten); // actual number written

 

if (!fSuccess)

printf("WriteConsoleOutputCharacter() failed.\n");

else

printf("WriteConsoleOutputCharacter() is OK.\n");

 

// Set 30-by-20-character screen buffer colors to white text on red.

wColor = BACKGROUND_RED | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;

fSuccess = FillConsoleOutputAttribute(

hStdOut, // screen buffer handle

wColor, // color to fill with

30*20, // number of cells to fill

coord, // first cell to write to

&cWritten); // actual number written

 

if (!fSuccess)

printf("WriteConsoleOutputAttribute() failed.\n");

else

printf("WriteConsoleOutputAttribute() is OK.\n");

return 0;

}

 

Output example:

 

GetStdHandle() is OK.

GetConsoleScreenBufferInfo() is OK.

WriteConsoleOutputCharacter() is OK.

WriteConsoleOutputAttribute() is OK.

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index