## Monday, November 21, 2011

### Draw a 3D Chess Board using OpenGL utility toolkits (GLUT), a graphics project with source code

This program  may help you in graphics project of your college.I simply  tries to draw the 3D Chess Board.  For this our main goal is to draw white and black rectangular box alternately along both x and y-axis.Drawing rectangular box is simple ,it is drawn by providing all side co-ordinates with the help of glVertex3f function and only top face is assign with black or white color and other face with brown color with the help of glColor3f function. I have made two function void draw_BlackArea() and void draw_whiteArea() to draw black and white square box respectively .Inside two for loop I have call these function by creating displaylist and with the help of glTranslatef(GLfloat x,GLfloat y,GLfloat z) function I draw  alternatively by translating their position.

## Tuesday, November 15, 2011

### Draw Reflection of Object on the floor using OpenGL Utility Toolkit (GLUT)

Drawing reflection capture the extra realism of the Object in 3D programming.For example Bouncing ball having its reflection on the floor can make the bouncing scenario more beautiful and realistic. So,OpenGL has all the features needed to render fast high-quality reflections on planar surfaces.
Reflection technique is not so hard its pretty simple.If you want to draw reflection on floor then suppose your floor is in x-z plane and your object along positive y-axis above the plane then for reflection of object draw the copy of object along the negative y-axis vertically below the plane or floor.Your floor must look like the reflecting surface to see the object which is below the floor for this we use alpha blending which make the floor transparent by certain percent say 40% then it is specified to be 40% the color of the floor and 60% the color of the reflection or object.But only alpha blending doesn’t make the reflection real because the reflected copy of the object may leak outside or bottom of the floor so to fixed this problem we actually going to use the stencil buffer concept.With OpenGL stenciling, we can "pre-draw" the floor into the stencil buffer without updating the color or depth buffers. Then when we go to draw the reflection,  just only allow the reflection to update pixels marked as belonging to the floor's stencil value. The floor can then be any complex (but coplanar) polygon and the reflection only shows up in the floor.

### Drawing a Bitmapped Character or string in OpenGL sample example

A bitmap is a rectangular array of 0s and 1s that serves as a drawing mask for a corresponding rectangular portion of the window. Suppose you're drawing a bitmap and that the current raster color is red. Wherever there's a 1 in the bitmap, the corresponding pixel is replaced by a red pixel and If there's a 0 in the bitmap, the contents of thepixel are unaffected. The most common use of bitmaps is for drawing characters on the screen.
In the simple example we use two main function glBitmap and glRasterPos2i function.
The glBitmap function draws a bitmap.

## Saturday, November 12, 2011

### Rotate an Object in OpenGL(GLUT) sample example with source

In GLUT we rotate the object by glRotate3f(angle_rotation,GLfloat x, GLfloat y ,GLfloat z) function angle_rotation parameter is value of angle to rotate and x,y,z co-ordinate are axis of rotation.But it does not rotate object continuously for that we have to change angle of rotation by small amount of increment. We do this by using timer thread with the help of glutTimerFunc function.Here is the sample source code copy and compile it.

## Friday, November 11, 2011

### How to change the color of object in OpenGL(GLUT) using keyboard function

If you have problem in changing color of object in OpenGL using keyboard while running program then this article may help you.Simply we can’t change the color of object while running for this we have to create a timer thread by using
Void  glutTimerFunc(unsigned int msecs,void (*func(int value),value)  function or other techinque can also be use.
Parameter:
msecs

Number of milliseconds to pass before calling the callback.

func

The timer callback function.

value

Integer value to pass to the timer callback.

## Friday, October 14, 2011

### Simple Multithreading Application sample source code in pure C

In our general program we can’t run two process at same time for e.g we can’t run two for loop at same time.For running two process at same time we need Multithreading.In C we do it by the _beginthread and
_endthread run time  library function.All the above c run time library functions are in the process.h header file.

process.h

Prototype

unsigned long _beginthread(void(* func)(void*), unsigned stack_size, void *arg);

Description

## Thursday, October 13, 2011

### Generate random number in C++

Random number is generated by using srand(time(NULL)) and rand() function.For time we have to include time.h and for srand() and rand function we have to include stdlib.h.Here is the simple program which generate 10 random number.
`#include<iostream>`
`#include<time.h>`
`#include<stdlib.h>`
`#define MAX_NUM 10`
`using namespace std;`

## Tuesday, October 11, 2011

### Conversion of infix operation to postfix and simple calculator

This code is to convert infix operation to postfix operation .This is the application of stack.Example infix  8*5+(5-3+1) converted to 85*53-1++ and result is 43.This program can be use as a simple calculator where user can calculate any result only in single step.
Copy the code and compile it in codeblock.

## Monday, October 10, 2011

### Winsock Programming sample project cyber management system.

Cyber Management System is a program which interconnects different computers which allows users to communicate over the computer network and provide security from unauthorized users by login system in client server.
The project is based on the client server architecture and its communication protocols. The project basically is divided into two sections:- Cyber server and Client server. Not only a single, multiple client can connect to cyber server at any time. Cyber server has the full control over Client server. Client server is password protected user has to login to access internet and other services. New user can signup for username and password. Price rate and services is fixed by cyber server. Client can request any service sending message to cyber server.

Major component

socket API

syntax:
int socket( int domain , inttype , intprotoco ) ;

### Scanning pdf file in hard drive or folder source code in c++

This program use the batch processing.For batch processing we use Frofiles.exe command.
```Syntax
FORFILES [/p Path] [/m Mask] [/s] [/c Command] [/d [+ | -] {dd/MM/yyyy | dd}]

Parameter List:
/P    pathname      Indicates the path to start searching.
The default folder is the current working directory (.).```

/S                  Instructs forfiles to recurse into subdirectories. Like "DIR /S".

/C    command       Indicates the command to execute for each file.
Command strings should be wrapped in double quotes.

The default command is "cmd /c echo @file".

## Sunday, October 9, 2011

### Playing sound source code in C++

This source code is not for playing songs or sound clips from your hard drive only to play  sound by using windows function Beep(int dwFreq [in],int dwDuration [in]) .
Parameters are
dwFreq [in]
The frequency of the sound, in hertz. This parameter must be in the range 37 through 32,767                      (0x25 through 0x7FFF)
dwDuration [in]
The duration of the sound, in milliseconds.
If the function succeeds, the return value is nonzero.If the function fails, the return value is zero. To get extended error information, call GetLastError.
This source code play the music “twinkle twinkle little star” using windows command Beep.Here is the source code copy it and compile and run in code::blocks IDE.

## Monday, September 19, 2011

### Analog Clock source code using c++ and winBGI graphics

The is the sample example of a WinBGIm graphics library implementation. The program will create an Analog clock using WinBGIm library. WinBGIm library does not come by default in Codeblocks IDE. You have to setup WinBGIm library before using the below code. If you haven't done it yet then please follow my earlier article How to Setup WinBGIm graphics in Codeblocks.

``````
#include <graphics.h>
#include <winbgim.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <conio.h>
#include <math.h>
#include <dos.h>
#include <string.h>
#include <iostream>
#include <ctime>

#define S_N_L (radius-10)        // Second Needle Length
#define S_N_C RED                   // Second needle Color
#define M_N_L (radius-20)           // Minute Needle Length
#define M_N_C LIGHTRED              // Minute Needle Color
#define H_N_C CYAN                     // Hour Needle Color

float cx,cy;

void get_time(int &h,int &m,int &s);
void second_needle(int s);
void minute_needle(int m,int s);
void hour_needle(int h,int m,int s);

int main(void)
{
/* request auto detection */
int gdriver = DETECT, gmode, errorcode;
initgraph(&gdriver,&gmode,"");
/***********************************/
cx=getmaxx()/2.0; // cx is center x value.
cy=getmaxy()/2.0; // cy is center y value.
/** Now the point (cx,cy) is the center of your screen. **/

float x,y;
int hour,minute,second;
while(!kbhit())
{
get_time(hour,minute,second);
second_needle(second);
minute_needle(minute,second);
hour_needle(hour,minute,second);
circle(cx,cy,2);
delay(100);
}
getch();
closegraph();
return 0;
}
//*************** FUNCTIONS DEFINITIONS *****************//

{
int theta=0; // theta is the angle variable.
float x,y;
/** Draw Clock Border. **/
/** Draw GREEN material border. **/
setcolor(BROWN);    // I like a wooden frame!
/** Paint the border. **/
for(int i=0;i<9;i++)
/** Set the color white. **/
setcolor(WHITE);
/** Draw outer-inner border. **/
/** Draw center dot. **/
circle(cx,cy,2);
int i=0;
/** DRAW NUMERIC POINTS **/
do{
/** Getting (x,y) for numeric points **/
/** Draw Numeric Points **/
circle(x,y,2);
/* Draw Dots around each numeric points **/
circle(x+5,y,0);
circle(x-5,y,0);
circle(x,y+5,0);
circle(x,y-5,0);
/** Increase angle by 30 degrees,
which is the circular distance between each numeric points. **/
theta+=30;
/** Increase i by 1. **/
i++;

} while(i!=12); //LIMIT NUMERIC POINTS UPTO =12= Numbers.
i=0;
/** DRAW DOTS BETWEEN NUMERIC POINTS. **/
do{
i+=6;
}while(i!=360);

/** FACE COMPLETELY DRAWN. **/
}
//================
/** Function to get the current time. **/
void get_time(int &h,int &m,int &s)
{
time_t rawtime;
struct tm *t;
time(&rawtime);
t = gmtime(&rawtime);
h=t->tm_hour;
m=t->tm_min;
s=t->tm_sec;
}
//=================
/** Function to draw Second needle. **/
void second_needle(int s)
{
float angle=-90;
float sx,sy;
setcolor(0);
sx=cx+S_N_L*cos((angle+s*6-6)*M_PI/180);
sy=cy+S_N_L*sin((angle+s*6-6)*M_PI/180);
line(cx,cy,sx,sy);
setcolor(S_N_C);
sx=cx+S_N_L*cos((angle+s*6)*M_PI/180);
sy=cy+S_N_L*sin((angle+s*6)*M_PI/180);
line(cx,cy,sx,sy);
}
/** Function to draw Minute needle. **/
void minute_needle(int m,int s)
{
float angle=-90;
float sx,sy;
setcolor(0);
sx=cx+M_N_L*cos((angle+m*6-6)*M_PI/180);
sy=cy+M_N_L*sin((angle+m*6-6)*M_PI/180);
line(cx,cy,sx,sy);
setcolor(M_N_C);
sx=cx+M_N_L*cos((angle+m*6/*+(s*6/60)*/)*M_PI/180);
sy=cy+M_N_L*sin((angle+m*6/*+(s*6/60)*/)*M_PI/180);
line(cx,cy,sx,sy);
}
/** Function to draw Hour needle. **/
void hour_needle(int h,int m,int s)
{
float angle=-90;
float sx,sy;
setcolor(0);
sx=cx+H_N_L*cos((angle+h*30-(m*30/60))*M_PI/180);
sy=cy+H_N_L*sin((angle+h*30-(m*30/60))*M_PI/180);
line(cx,cy,sx,sy);
setcolor(H_N_C);
sx=cx+H_N_L*cos((angle+h*30+(m*30/60))*M_PI/180);
sy=cy+H_N_L*sin((angle+h*30+(m*30/60))*M_PI/180);
line(cx,cy,sx,sy);
}
``````

### How to Setup WinBGIm library in Codeblocks IDE

BGI (Borland Graphics Interface) is a very old graphics library available in Borland C++ and Turbo C++ IDE. Borland c++ and Turbo C++ both were discontinued. BGI graphics library was very popular, and still, students in our schools and colleges want to use it in their projects. Codeblocks IDE with MinGW compiler is widely used as C/C++ especially to develop cross-platform open-source software but BGI is not available in Codeblocks. Thanks to Michael Main, who created WinBGIm at the University of Colorado to use the BGI graphics library in windows with other compilers. There are many alternatives to winBGIm, But BGI is good for beginners because you don’t have to worry about whole new fancy functions, classes, etc.

However, the latest version of WinBGIm was released in Nov 2005 which is very old and no longer supported in a newer version of the MinGW compiler. We have to compile source code to make it run in the latest Codeblocks. In this article, I will provide instructions to compile source code and configure the library in Codeblocks IDE. I have also created a video about it. You can watch below:

If you don’t want to compile source code and fix errors by yourself then copy project files from my github https://github.com/smokindinesh/WinBGIm and go to configure library section.

Lets get started: Create Static Library Project
3. Open Codeblocks and create a new project. (File -> New -> Project)
4. From the Project template window select "Static Library" and fillup all necessary information to finish the project creation wizard.
5. Go to project properties and select "Build targets" option and rename output filename with libbgi.a for both debug and release targets.
6. Copy all source files that you have extracted in the earlier step and paste them to the project directory.
7. Remove "main.c" file from the project.
8. Add source files in the project (Select project in Workspace -> Right Click -> Add Files recursively). Select both Build and Release options in the Target window which pops-up after adding files.
9. Now, a project is ready to build but there are errors in the source code. Please follow the instructions provided below to fix errors.

Instruction to fix errors:
• Source file "bgiout.cxx"
• Line 1: Replace '#include <stringstream>' with '#include <sstream>'
• Line 2: Remove ': virtual std::basic_ostringstream'
• Source file "winbgim.h"
• Line 302: Replace "right=0" with "top=0"
• Source file "graphics.h"
• Line 302: Replace "right=0" with "top=0"
• Source file "misc.cxx"
• Line 595 to 599: Remove "~". e.g Replace ~0xE0 with 0xE0.
• Line 103: Replace "SetWindowLong( hWindow, GWL_USERDATA, (LONG)pWndData )" with "SetWindowLongPtr( hWindow, GWLP_USERDATA, (LONG_PTR)pWndData )"
• Source file "drawing.cxx"
• Line 66: Replace "return (WindowData*)GetWindowLong( hWnd, GWL_USERDATA )" with "return (WindowData*)GetWindowLongPtr( hWnd, GWLP_USERDATA );"
• Note: In above steps 5 and 6, if GWLP_USERDATA didnot work then try with GWL_USERDATA
• Finally, compile project in Release target. I hope you will not encounter any other errors.

Configure winbgim library in Codeblocks.
1. Create a folder in any directory and give the name "WinBGIm" and create include and lib folder inside it. (eg. c:\WinBGIm\include and c:\WinBGIm\lib).
2. From the project created above, copy "graphics.h" and "winbgim.h" header files and paste it inside include directory, and "libbgi.a" file from bin/release project folder and paste it inside lib directory that you have created in step 2. (eg. c:\WinBGIm\include and c:\WinBGIm\lib).
3. Open the code::blocks and go to File -> New -> Project or click create a new project link from the start page.
4. From the project wizard select "empty project" and click "Go" button and provide all necessary information. Also, do not forget to  add main.cpp file.
5. Go to menu bar and select project-> Project properties. A dialogue box will appear and click "Project's build options". Another dialogue box will appear and click the "Search directories" tab. Under "Compiler" tab provide the path of WinBGIm include folder (e.g. c:\WinBGIm\include) and under "Linker" tab provide the path of WinBGIm lib folder (e.g. c:\WinBGIm\lib).
7. Now click ok.

Finally, you can now compile source code using "graphics.h". To test configuration please copy source code from the sample winBGIm graphics program from here. I hope, you found this guide helpful, and in case you need my help just leave a message.

## Thursday, September 15, 2011

### College project Contacts Management in C with source code

In this article, we will create a contact management system in C and store data in the file. You will learn CRUD (Create, Read, Update, and Delete) operation in C files, and various modes of opening files. The main objective of this article is to give you an idea of file handling in C programming.

At the end of this article, you will learn the following items:
• Break down the application into separate individual modules.
• Create an application flow chart.
• Convert the flow chart processes into C functions.
• Learn techniques to switch between processes based on the user input.
• Master the CRUD (Create, Read, Update, and Delete) operation in file handling.

For a detailed explanation follow the articles below.

Chapter 1 -> Flow chart and Functions: In this article, you will learn to create a flow chart, breakdown the application into C functions, and create a Main Menu function to display options and get user input.
Chapter 2 -> File handling in C: In this article, you will learn to add, read, update, and delete data from the file

## Thursday, June 30, 2011

### BItmap maping and texture map in OpenGL

This the sample code for texture map in teapot and bit map is used to draw chess board.Code is compiled in codeblocks you can copy and paste this code for your study or project.Please use your own image for texture map.Image must be in bmp formate.

#include <windows.h>
#include <GL/glut.h>
#include <stdio.h>
GLuint texture[2];
GLint slices=16;
GLint stacks=16;
struct Image {
unsigned long sizeX;
unsigned long sizeY;
char *data;
};
typedef struct Image Image;

## Thursday, June 23, 2011

### Mini project tic-tac-toe game source code in C

Hi this is a tic-tac-toe game you can copy sourcecode here or Download from GitHub.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include <windows.h>

## Tuesday, June 21, 2011

### Mini project Quiz in C

You will learn to break down an application into modules (functions), switch between screens based on user input, multi-dimensional array techniques, loops and so much more.

Like in other sample mini-projects, I have not used a file handling system to store information to make it simple and easy to understand basic techniques.

• Truly understand how to break down the application and create a flow chart.
• Be able to convert the flow chart processes into C functions.
• Learn techniques to switch between processes based on user input.
• Have mastered the usages of multi-dimensional C arrays and loops.

Part 1: Flow Chart and Main Menu: In this lesson, you will learn to create an application flow chart and create a welcome menu screen of the game.
Part 2: Multi-dimensional C array: In this lesson, you will understand techniques to create a function and switching between multiple functions as per user choice. You will master how to use one-dimensional, two-dimensional, and three-dimensional C arrays to store questions, question options, and answers.
Part 3: Gameplay and the final score: You will learn to use a loop to display questions one by one, check the user's correct answer, and calculate the final score.

### mini project Department store source code

This mini project is about department store all features required for department store are added in this programe.You can copy the source code and compile it in a code block.This project is perfect for your college mini project in C. Download Project from Github

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#include<windows.h>

#define ANS 15
#define ACS 4
COORD coord={0,0}; // this is global variable
//center of axis is set to the top left cornor of the screen
void gotoxy(int x,int y)
{
coord.X=x;
coord.Y=y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
}
/*declaration of checking functions*/
void c_code(char[]);
int check(char[]);

/*structure declaration*/
typedef struct{
char name[ANS],code[ACS];
float rate;
int quantity;
}rec;
rec item;

/*declaration of display functions*/
void curser(int);
void dbill();
void display(rec *,int,int);
void window(int,int,int,int);
void dis_con();
void d_search();
void highlight(int,int);

void bill() ;
void edit();
void del();
void exit();

void d_code();
void d_rate();
void d_quan();
void d_all();

/*start of main*/
int main()
{
return 0;
}

## Sunday, June 19, 2011

### Mini project snake game in c

Mini project in C many Student do management project like library management ,Hotel management etc.But Snake Game is mini project of first semester build by my friend which is very different.It is console application without graphic library that's why it is more interesting.This game is perfect without any error and better user interface.It is complied in code::block using c language.Here goes a source code you can copy and compiled it in code::block.I hope it can help and become a reference for your project. Download Project from Github.

## Friday, June 17, 2011

### Mini project "3D Bounce " in OpenGL

This project is my second-year mini-project. I have use the GLUT(OpenGL) library in c++.3D Bounce is a game in which we have to bounce the ball to collect the floating star,after collecting all star then a door opens for the next room. Due to lack of time, I can't complete this project but all image drawing part is completed and I hope you will complete it for your collage project.You can download it source code from this link http://www.4shared.com/file/J-cjGaN-/bounce.html .This program is written in complete object oriented environment ,I have made different class in different file and It's code is very lengthy so  I can't give source code here.

## Wednesday, June 15, 2011

### Drawing a snowman using OpenGL source code

This source code is written in c using the OpenGL library. This program is just a demo to draw a different shape object and I draw a man like an object in this program. I have also added a keyboard event in this program.

#include <math.h>
#include <GL/glut.h>
#include <stdio.h>
#include <string.h>
//#include <cstdlib>
//if you got error in exit() by compiler then does not incluede stdlib.h because //exit() is also defined in glut.h file.

float angle=0.0,deltaAngle = 0.0,ratio;
float x=0.0f,y=1.75f,z=5.0f;
float lx=0.0f,ly=0.0f,lz=-1.0f;
int deltaMove = 0,h,w;
int font=(int)GLUT_BITMAP_8_BY_13;
static GLint snowman_display_list;
int bitmapHeight=13;

int frame,time,timebase=0;
char s[30];

void initWindow();

void changeSize(int w1, int h1)
{

// Prevent a divide by zero, when window is too short
// (you cant make a window of zero width).
if(h1 == 0)
h1 = 1;

w = w1;
h = h1;
ratio = 1.0f * w / h;
// Reset the coordinate system before modifying
glMatrixMode(GL_PROJECTION);

// Set the viewport to be the entire window
glViewport(0, 0, w, h);

// Set the clipping volume
gluPerspective(45,ratio,0.1,1000);
glMatrixMode(GL_MODELVIEW);
gluLookAt(x, y, z,
x + lx,y + ly,z + lz,
0.0f,1.0f,0.0f);

}

## Sunday, June 12, 2011

### Mouse event handling source code in OpenGL

This source code is written in C++ with OpenGL.It is just a demo for mouse event handling you can use this code for your project. In this example void motionPassive(int x, int y) to find out the cursor position in the window. By finding the difference between the previous and initial position the direction of the camera is changed.

### Texture map in solid sphere using GLUT(OpenGL)

This source code is written in C used to draw a solid sphere using OpenGL and you can map texture in it. Create a project for OpenGL and copy and paste this code and use your desire image file for texture mapping.

//main.c

#include <GL/gl.h>
#include <GL/glut.h>
#include <windows.h>
#include <stdio.h>
#include <math.h>
GLuint texture;
double angle = 0;
typedef struct
{
int X;
int Y;
int Z;
double U;
double V;
}VERTICES;

const double PI = 3.1415926535897;
const int space = 10;
const int VertexCount = (90 / space) * (360 / space) * 4;
VERTICES VERTEX[VertexCount];
GLuint LoadTextureRAW( const char * filename );

## Saturday, March 19, 2011

### Digital clock implementation in C using time.h header

This sample application is the implementation of the clock() function available in time.h header. The time function is very useful and necessary. Some of the examples of usage of time function are:
• Security applications might need to update the security keys every one minute or more.
• You may need to write a function to send files to the remote server every one minute or extract files from the server every 15 minutes.
and many more.

I have created a simple digital clock to show you the implementation of clock() function. The sample code given below is written in C using codeblocks IDE on windows.
``````
#include <stdio.h>
#include <time.h>         //this is header file for time
#include <windows.h>

COORD coord = {0, 0};
void gotoxy (int x, int y)
{
coord.X = x;
coord.Y = y; // X and Y coordinates
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

int main()
{

long i = 0;                      /* Loop counter              */
clock_t now = 0;                 /* Holds initial clock time  */
int interval = 1;                /* Seconds interval for o/p  */
int elapsed = 0;
int min=0,MIN=0,hrs=0,sec=0;
int d=0,f=0;
now = clock(); /* Get current clock time    */

for(i = 0L ;  ; i++)
{
elapsed = (clock()-now)/CLOCKS_PER_SEC;

if(elapsed>=interval)
{
interval += 1;
if(elapsed%60==0)
{
min=elapsed/60;
d=60*min;
if(min%60==0)
{
hrs=min/60;
f=60*hrs;
}
}
sec=elapsed-d;
MIN=min-f;
if(hrs<10)
{
gotoxy(2,4);
printf("0%d",hrs);
}
else
{
gotoxy(2,4);
printf(":%d",hrs);
}
if(min<10)
{
gotoxy(4,4);
printf(":0%d",MIN);
}
else
{
gotoxy(4,4);
printf(":%2d",MIN);
}

if(sec<10)
{
gotoxy(7,4);
printf(":0%d",sec);
}
else
{
gotoxy(7,4);
printf(":%2d",sec);
}
gotoxy(7,7);
printf("%dhrs:%dmin:%dsec",hrs,MIN,sec);
}
}

return 0;
}``````

### Resize and Move Console Window in C/C++ using windows function

This is another article related to the window.h library function. Here I will take you through resizing the console window and moving it on the screen at the desire position. Using window.h library function is the only option to control console windows if you are not using third-party graphics library. Resizing and moving console window function is useful if your application needs to create multiple windows and position it as per requirement.
Note: Below sample C code works only in the windows environment.
``````
#include <windows.h>
#include <stdio.h>

HWND WINAPI GetConsoleWindowNT(void)
{
//declare function pointer type
typedef HWND WINAPI(*GetConsoleWindowT)(void);
//declare one such function pointer
GetConsoleWindowT GetConsoleWindow;
//get a handle on kernel32.dll
HMODULE hk32Lib = GetModuleHandle(TEXT("KERNEL32.DLL"));
//assign procedure address to function pointer
,TEXT("GetConsoleWindow"));
//check if the function pointer is valid
//since the function is undocumented
if(GetConsoleWindow == NULL){
return NULL;
}
//call the undocumented function
return GetConsoleWindow();
}
int main()
{
HWND hWnd=GetConsoleWindowNT();
MoveWindow(hWnd,1230,600,300,200,TRUE);
}
``````
I suggest you to test the parameters values of the function MoveWindow because the maximum value depends upon the size of the laptop or monitor screen.

### Change console windows background color in C

In my earlier article changing text color in codeblock and text background color of console, I had provided a sample source code to change text color and text background color using windows.h library function. Similarly, we can also change console windows background color using windows.h library function. Here, I have shared a sample source code to change the console windows background color. The sample program is written in C.
``````
#include <windows.h>          //header file for windows
#include <stdio.h>

void ClearConsoleToColors(int ForgC, int BackC);
int main()
{
ClearConsoleToColors(0,1);
Sleep(1000);
return 0;
}
void ClearConsoleToColors(int ForgC, int BackC)
{
WORD wColor = ((BackC & 0x0F) << 4) + (ForgC & 0x0F);
//Get the handle to the current output buffer...
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
//This is used to reset the carat/cursor to the top left.
COORD coord = {0, 0};
//A return value... indicating how many chars were written
//   not used but we need to capture this since it will be
//   written anyway (passing NULL causes an access violation).
DWORD count;

//This is a structure containing all of the console info
// it is used here to find the size of the console.
CONSOLE_SCREEN_BUFFER_INFO csbi;
//Here we will set the current color
SetConsoleTextAttribute(hStdOut, wColor);
if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
{
//This fills the buffer with a given character (e.g 32=space).
FillConsoleOutputCharacter(hStdOut, (TCHAR) 32
, csbi.dwSize.X * csbi.dwSize.Y, coord, &count);

FillConsoleOutputAttribute(hStdOut, csbi.wAttributes
, csbi.dwSize.X * csbi.dwSize.Y, coord, &count );
//This will set our cursor position for the next print statement.
SetConsoleCursorPosition(hStdOut, coord);
}
return;
}
``````
You can change console windows background color by passing integer value range 0 up-to 256 in ClearConsoleToColors(int ForgC, int BackC) function.

### Change text background color in C console application

Usually, console applications are black and white. However, sometimes for specific purposes, we may need to change the text background color to highlight the specific texts. Changing text background color in the console is challenging especially if you are using Codeblocks MinGW. Unlike turbo c/c++ GCC does not provide the function to change the text background color. If you want to change the text background color then we should use windows.h library function. You can find the sample code below which change text background color. The sample program is written in C utilizing windows.h library function.
``````
#include <windows.h>         //header file for windows
#include <stdio.h>           //C standard library
void SetBackgroundColor(int BackC);
int main(){

int i=0;
for(i=0; i<256; i++){
SetBackgroundColor(i);
printf("Test Text Background Color for value i: %d\n",i);
}
getch();

return 0;
}
void SetBackgroundColor(int BackC)
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
WORD wColor = ((BackC & 0x0F) << 4) + (csbi.wAttributes & 0x0F);
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), wColor);
return;
}``````
In output program, for every 16 values (0-15, 16-32, etc) text colors will repeat. It means in this method we get only 4 bit color space i.e only 16 colors. You can change your desired text background color by passing integer value range 0 up to 15 in SetBackgroundColor() function.

### Change text color in C console application

Usually, console applications are black and white. However, sometimes for specific purposes, we need to change the text color to highlight the specific values, dates, or texts. Changing text color in the console is challenging especially if you are using Codeblocks MinGW. Unlike turbo c/c++ GCC does not provide the function to change text color. If you want to change the text color to make console windows colorful then we should use windows.h library function. You can find the sample code below which change text color. The sample program is written in C utilizing windows.h library function.
``````
#include <windows.h>         //header file for windows
#include <stdio.h>           //C standard library
void SetColor(int ForgC);
int main(){

int i=0;
for(i=0; i<256; i++){
setColor(i);
printf("Test Color Text for value i: %d\n",i);
}
getch();

return 0;
}

void setColor(int ForgC){

//We will need this handle to get the current background attribute
WORD wColor;

HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);

//we use csbi for the wAttributes word.
CONSOLE_SCREEN_BUFFER_INFO csbi;

if(GetConsoleScreenBufferInfo(hStdOut, &csbi)){
//Mask out all but the background attribute
//, and add in the foreground color
wColor = (csbi.wAttributes & 0xF0) + (ForgC & 0x0F);
SetConsoleTextAttribute(hStdOut, wColor);
}
return;
}``````

In output program, for every 16 values (0-15, 16-32, etc) text colors will repeat. It means in this method we get only 4 bit color space i.e only 16 colors. You can change your desired text color by passing integer value range 0 up to 15 in SetColor() function.

## Thursday, March 17, 2011

### gotoxy function in Codeblocks

gotoxy(int x, int y) a function available in Turbo C/C++. It is not standard C. This function is used to move the cursor on the screen to the desire location. The top left corner of the monitor is 0,0 and the bottom right corner might be any number based on the size of the screen. But today's standard C++ compiler such as Visual Studio, GCC and clang do not provide gotoxy function. However, if you are developing console applications without a third party graphic library then gotoxy function is useful to manage text alignment on the screen.

If you need similar implementation on a windows machine with GCC compiler then here is an example source code.
``````#include <windows.h>    //  header file for gotoxy
#include <iostream> //header file for standard input output
COORD coord= {0,0}; // this is global variable
void gotoxy(int x,int y)
{
coord.X=x;
coord.Y=y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
}

int main()
{
//calling these function
int x;
gotoxy(15,5);
std::cout<<"1. This is item number one.";
gotoxy(15,7);
std::cout<<"2. This is item number two.";
gotoxy(15,9);
std::cout<<"3. This is item number three.";
gotoxy(15,11);
std::cout<<"4. This is item number four.";
gotoxy(15,13);
std::cout<<"5. This is item number five.";
std::cin>>x;
return 0;
}``````
Please watch the video below for detailed explanation.

## Sunday, March 13, 2011

### Mini project library management in C programming

The project, “Library Management in C,” is larger and more complex than my other projects, such as the Quiz game, Contact Management, and Personal Diary Management. In this project, I have implemented a variety of techniques and features, including Admin and Student modes, user security, reading and writing CSV files, and many others. This project will provide you with numerous insights. If you’re aiming for the highest grade in your project/lab assignment, I recommend following this project.

The main objective of this project is to introduce you to the following techniques and features:
• Breaking down the application and representing it with a flowchart
• Creating a function call stack diagram
• Creating an application menu and navigating in and out of the user screens
• Reading and writing data from and into a CSV file
• Dynamic memory allocation to create dynamic array
•  Add and delete data from dynamic memory array.
• Performing CRUD (Create, Read, Update, and Delete) operations in C file handling
• Implementing many utility functions such as converting an integer to a string, a string to an integer, hiding password by displaying asterisks
In this article, I will not explain each and every function of the application. The style of creating a user menu and the technique of switching in and out of the screens, C file handling is the same as in other projects. Here, I will explain the flowchart, function call stack diagram, and major functions such as the login system, reading and writing CSV files, and other major and complex functions.

## Sunday, February 27, 2011

### Setup GLFW 3 library in Codeblocks IDE

GLFW is a free, open-source, multi-platform library for OpenGL and OpenGL ES especially design for game development. OpenGL itself does not provide features to handle window creation and other input, so GLFW is very useful to create the necessary context, manage windows, timing, read and control user input via keyboard, mouse, joysticks and other purposes. There are many other library alternatives to GLFW such as SDL and freeglut but if you are looking best library for 3D game development then GLFW is best. GLFW community is large and very active, at the time of updating this article latest stable version of GLFW is 3.3.2 which is released on January 20, 2020. It comes with documentation, high standard tutorials and guides and lots of test programs.

Here, I will guide you through a step by step procedure to setup GLFW 3 in Codeblocks IDE on Windows 10.

Visit GLFW download page https://www.glfw.org/download.html and download 32 bit/64 bit windows binary files from the Windows pre-compiled binaries section. You have to make sure that bit of your C++ compiler and downloaded GLFW library files should match. Currently, GLFW releases are tested with MinGW, MinGW-w64 and Visual C++ 2010 and above version.

Steps to setup GLFW library and create a project in Code::blocks:
2. Create a folder in any directory and give a name "GLFW" (eg. c:\GLFW).
3. Browse extracted files in step 1. Copy "include" folder and paste it inside the directory that you have created in step 2. Copy lib folder of corresponding to your compiler for e.g if you are using minGW then copy lib-mingw folder and paste it inside the directory that you have created in step 2 and rename it to lib. Also copy glfw3.dll file from bin folder to "C:\Windows\System32" if you are using 32-bit library files or copy to "C:\Windows\System" if you are using 64-bit library files.
4. Now, open the code::blocks and go to File -> New -> Project or click create a new project link from the start page.
5. From the project wizard select "empty project" and click "Go" button and provide all necessary information. Also, do not forget to add main.cpp file.
6. Go to the menu bar and select project-> Project properties. A dialogue box will appear and click "Project's build options". Another dialogue box will appear and click the "Search directories" tab. Under the "Compiler" tab add the path of GLFW include folder (e.g. c:\GLFW\include) and under "Linker" tab add the path of GLFW lib folder (e.g. c:\GLFW\lib).
7. Now go to "Linker Setting" tab and add three linker libglfw3.a, libglfw3dll.a and libopengl32.a. Linker libglfw3.a and libglfw3dll.a are available inside GLFW lib folder and libopengl32.a is available inside minGW compiler lib folder.
Copy and paste below code in main.cpp file and compile it to verify GLFW library setup.
``````
#define GLFW_DLL
#include <GLFW/glfw3.h>
#include <iostream>
#include <stdexcept>

GLFWwindow* window = NULL;
GLFWmonitor* monitor = NULL;

int main(int argc, char *argv[]) {

if(!glfwInit())
throw std::runtime_error("glfwInit failed");

window = glfwCreateWindow(800, 600, "test window",NULL, NULL);
if(!window)
throw std::runtime_error("glfwOpenWindow failed.");

// GLFW settings
glfwMakeContextCurrent(window);

while(!glfwWindowShouldClose(window)){
// process pending events
glfwPollEvents();
glClearColor(1, 0, 0, 1); // black
glClear(GL_COLOR_BUFFER_BIT);
glfwSwapBuffers(window);
}
// clean up and exit
glfwTerminate();
return 0;
}``````

You have to make sure to define GLFW_DLL  and include glfw3.h header always on top of your source code as shown in the above sample code otherwise the compiler will throw undefine reference error.

Please watch the video below for a detailed explanation.

## Friday, February 25, 2011

### Setup Code::blocks in Windows 10 and It's Features

 Features

### Highlights:

• Open Source! GPLv3, no hidden costs.
• Cross-platform. Runs on Linux, Mac, Windows (uses wxWidgets).
• Written in C++. No interpreted languages or proprietary libs needed.
• Extensible through plugins

### Compiler:

• Multiple compiler support:
• GCC (MingW / GNU GCC)
• MSVC++
• Digital Mars
• Borland C++ 5.5
• Open Watcom
• ...and more
• Very fast custom build system (no makefiles needed)
• Support for parallel builds (utilizing your CPU's extra cores)
• Multi-target projects
• Workspaces to combine multiple projects
• Inter-project dependencies inside a workspace
• Imports MSVC projects and workspaces (NOTE: assembly code not supported yet)
• Imports Dev-C++ projects

## Tuesday, February 22, 2011

### Setup wxWidgets in Codeblocks

wxWidgets is free software, multi-platform GUI library written in C++ programing language. GUI applications created using the wxWidgets library run on multiple platforms such as Windows, Linux, Mac, and others that utilize the native platform's controls and utilities. Since it is built and compiled in C++, it has high performance and is nearly as fast as using the native toolkits themselves.

The Codeblocks IDE that we are using is also developed using wxWidgets. Here, I will guide you through a step-by-step procedure to set up wxWidgets in Codeblocks IDE on Windows.

Steps to setup wxWidgets library:
1. Extract downloaded zip files both "Header" and "Development Files". (Note: you may need 7zip to extract files)
2. Create a folder in any directory and give the name "wxWidgets" (eg. c:\wxWidgets).
3. Browse extracted files in step 1. Copy "include" folder from the downloaded Header and paste it inside the directory that you have created in step 2. Copy "lib"  folder from the downloaded Development Files and paste it inside the directory that you have created in step2. If you open "lib" folder you will find dll files, you can copy all dll files to "C:\Windows\System32" folder if you are using 32-bit or "C:\Windows\SysWOW64" folder if you are using 64-bit. However, I do not suggest you to copy dll files to the system folder in the development phase of an application.
4. Now, open the code::blocks and go to File -> New -> Project or click create a new project link from the start page.
5. From the project wizard select "empty project" and click "Go" button and provide all necessary information. Also, do not forget to add main.cpp file.
6. Go to the menu bar and select Project-> Properties. A dialogue box will appear and click "Project's build options". Another dialogue box will appear and click the "Search directories" tab. Make sure that in left side panel you must select "<project name>" and under the "Compiler" tab add the path of wxWidgets include folder (e.g. c:\wxWidgets\include) and under "Linker" tab add the path of wxWidgets lib folder (e.g. c:\wxWidgets\lib\gcc810_x64_dll) where you can find *.a and *.dll files.
7. Select "Debug" option in left side panel and click the "Search directories" tab. Under the "Compiler" tab add the path of folder "mswud". This folder is located inside wxWidgets lib folder (e.g. c:\wxWidgets\lib\gcc810_x64_dll\mswud). Note: if you are using 32-bit then the path might be different (e.g. c:\wxWidgets\lib\gcc_dll\mswud). Now select "Linker Setting" tab and add two linkers wxmsw31ud_core and wxbase31ud. Please type exactly the same name don't write "lib" prefix and ".a" extension.
8. Select "Release" option in left side panel and click the "Search directories" tab. Under the "Compiler" tab add the path of folder "mswu". This folder is located inside wxWidgets lib folder (e.g. c:\wxWidgets\lib\gcc810_x64_dll\mswu). Note: if you are using 32-bit then the path might be different (e.g. c:\wxWidgets\lib\gcc_dll\mswu). Now select "Linker Setting" tab and add two linkers wxmsw31u_core and wxbase31u. Please type exactly the same name don't write "lib" prefix and ".a" extension.
Please watch the video below for a detailed explanation.

Now copy the sample code given below inside "main.cpp" file and build and run it. Sample code is taken from wxWidgets official website.
``````
// wxWidgets "Hello World" Program
// For compilers that support precompilation, includes "wx/wx.h".
#include &lt"wx/wxprec.h"&gt
#ifndef WX_PRECOMP
#include &lt"wx/wx.h"&gt
#endif
class MyApp : public wxApp
{
public:
virtual bool OnInit();
};
class MyFrame : public wxFrame
{
public:
MyFrame();
private:
void OnHello(wxCommandEvent& event);
void OnExit(wxCommandEvent& event);
};
enum
{
ID_Hello = 1
};
wxIMPLEMENT_APP(MyApp);
bool MyApp::OnInit()
{
MyFrame *frame = new MyFrame();
frame->Show(true);
return true;
}
MyFrame::MyFrame()
: wxFrame(NULL, wxID_ANY, "Hello World")
{
"Help string shown in status bar for this menu item");
CreateStatusBar();
SetStatusText("Welcome to wxWidgets!");
}
void MyFrame::OnExit(wxCommandEvent& event)
{
Close(true);
}
{
wxMessageBox("This is a wxWidgets Hello World example",
"About Hello World", wxOK | wxICON_INFORMATION);
}
void MyFrame::OnHello(wxCommandEvent& event)
{
wxLogMessage("Hello world from wxWidgets!");
}
``````

### Setup GLUT (OpenGL) in Codeblocks

GLUT (OpenGL Utility Toolkit) is a toolkit to write OpenGL programs. It makes learning OpenGL programming very easy and simple. However, it is very old and unsupported for the last 20 years or more and it does not support modern requirements. I personally do not recommend this library and I request to choose one of the alternate libraries such as GLFW, freeglut, and SDL.

If you still need to setup this library to execute old code downloaded from the internet written in GLUT then follow the steps provided below:

Steps to create GLUT project in Code::block.

Step 2: Browse extracted files. Copy the glut.h file and paste it into the directory "C:\ProgramFiles(x86)\CodeBlocks\MinGW\include\GL". Copy glut.lib file and paste it into the directory "C:\Program Files(x86)\CodeBlocks\MinGW\lib". Also, copy the glut.dll and paste it into
the directory "C:\Windows\System32".

## Monday, February 21, 2011

### Setup SDL 2 in Codeblocks

#### Setup SDL 2 in Code::Blocks (modern version)

The latest stable version of SDL (Simple DirectMedia Layer) is 2.0.10 at the time of updating this article. Unlike SDL 1.2, SDL 2 utilizes GPU memory and provides features to develop high-performance games and applications. Also, it includes easy access to graphics, sound and input handling.
Here, I will guide you through a step by step procedure to setup SDL 2 in Codeblocks IDE on Windows 10.

Steps to create SDL 2 project in Code::blocks:
2. Create a folder in any directory and give a name "SDL 2" (eg. c:\SDL 2).
3. Browse extracted files in step 1. Copy "include" and "lib" folders and paste it inside the directory that you have created in step 2. Also, copy SDL.dll file from bin folder to "C:\Windows\System32" if you are using 32-bit library files or copy to "C:\Windows\System" if you are using 64-bit library files.
4. Open the code::blocks and go to File -> New -> Project or click create a new project link from the start page.
5. From the project wizard select "empty project" and click "Go" button and provide all necessary information. Also, do not forget to  add main.cpp file.
6. Go to menu bar and select project-> Project properties. A dialogue box will appear and click "Project's build options". Another dialogue box will appear and click the "Search directories" tab. Under "Compiler" tab provide the path of SDL include folder (e.g. c:\SDL2\include) and under "Linker" tab provide the path of SDL lib folder (e.g. c:\SDL2\lib).
8. Copy and paste below code in main.cpp file and compile it to verify SDL setup.

``````#include <SDL2\SDL.h>
#include <iostream>
//Screen dimension constants
const int SCREEN_WIDTH = 640,SCREEN_HEIGHT= 480;

int main( int argc, char* args[] ){
//The window we'll be rendering to
SDL_Window* window = NULL;
//The surface contained by the window
SDL_Surface* screenSurface = NULL;
//Initialize SDL
if( SDL_Init( SDL_INIT_VIDEO ) < 0 ){
std::cout<<"SDL_Error: %s\n"<<SDL_GetError()<<std::endl;
}else{
//Create window
window = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED
, SDL_WINDOWPOS_UNDEFINED
, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
if( window == NULL ){
std::cout<<"SDL_Error: %s\n"<<SDL_GetError()<<std::endl;
}else{
screenSurface = SDL_GetWindowSurface( window ); //Get window surface
SDL_FillRect( screenSurface, NULL
, SDL_MapRGB( screenSurface->format, 0x00, 0xFF, 0xFF ) );
//Fill the surface with color
SDL_UpdateWindowSurface( window ); //Update the surface
SDL_Delay( 2000 ); //Wait two seconds
}
}
SDL_DestroyWindow( window ); //Destroy window
SDL_Quit();  //Quit SDL subsystems
return 0;
}
``````

Please watch the video below for a detailed explanation.

#### Setup SDL 1.2 in Code::Blocks (old version)

Steps to create SDL 1.2 project in Code::blocks:
2. Create a folder in any directory and give a name "SDL 1.2" (eg. c:\SDL 1.2).
3. Browse extracted files in step 1. Copy "include" and "lib" folders and paste it inside the directory that you have created in step 2. Also, copy SDL.dll file from bin folder to "C:\Windows\System32" folder.
4. Open the code::blocks and go to File -> New -> Project or click create a new project link from the start page.
5. From the project wizard select "SDL project" and click "Go" button and provide all necessary information.

After creating a project, build and run the default program.

Please watch the video below for a detailed explanation.