You are on page 1of 133

Borland Graphics Interface (BGI

)
The following functions compose the Borland Graphics Interface and are usually available for
16 bit DOS applications. Use them to create onscreen graphics with text. They are defined in
graphics.h.
Using BGI with Windows
The BGI graphics functions may also be used with Windows programs created by the Borland
5.0 compiler or the free GNU C++ compiler. These extra functions are described in
www.cs.colorado.edu/~main/bgi/doc/bgi.html. In this listing, the extra functions are indicated
by . Also, any of the functions that use colors can use RGB colors in addition to the 16-
color BGI palette.
Functions:
void arc (int x, int y, int stangle, int endangle, int
radius);

void bar (int left, int top, int right, int bottom);

void bar3d (int left, int top, int right, int bottom, int
depth, int topflag);

void circle (int x, int y, int radius);

void cleardevice (void);

void clearmouseclick(int kind);

void clearviewport (void);

void closegraph (void);

void delay (int millisec);

void detectgraph (int *graphdriver, int *graphmode);

void drawpoly (int numpoints, int *polypoints);

void ellipse (int x, int y, int stangle, int endangle, int
xradius, int yradius);

void fillellipse (int x, int y, int xradius, int yradius);

void fillpoly (int numpoints, int *polypoints);

void floodfill (int x, int y, int border);

int getactivepage (void);

void getarccoords (struct arccoordstype *arccoords);

void getaspectratio (int *xasp, int *yasp);

int getbkcolor (void);

int getch (void);

int getcolor (void);

struct palettetype* getdefaultpalette (void);

char* getdrivername (void);

void getfillpattern (char *pattern);

void getfillsettings (struct fillsettingstype *fillinfo);

int getgraphmode (void);

void getimage (int left, int top, int right, int bottom,
void *bitmap);

void getlinesettings (struct linesettingstype *lineinfo);

int getmaxcolor (void);

int getmaxmode (void);

int getmaxx (void);

int getmaxy (void);

char* getmodename (int mode_number);

void getmoderange (int graphdriver, int *lomode, int
*himode);

void getmouseclick(int kind, int& x, int& y);

void getpalette (struct palettetype *palette);

int getpalettesize (void);

unsigned getpixel (int x, int y);

void gettextsettings (struct textsettingstype
*texttypeinfo);

void getviewsettings (struct viewporttype *viewport);

int getvisualpage (void);

int getx (void);

int gety (void);

void graphdefaults (void);

char* grapherrormsg (int errorcode);

int graphresult(void);

unsigned imagesize (int left, int top, int right, int bottom);

void initgraph (int *graphdriver, int *graphmode, char
*pathtodriver);

void initwindow (int width, int height);

int installuserdriver (char *name, int huge
(*detect)(void));

int installuserfont (char *name);

bool ismouseclick(int kind);

int kbhit (void);

void line (int x1, int y1, int x2, int y2);

void linerel (int dx, int dy);

void lineto (int x, int y);

int mousex (void);

int mousey (void);

void moverel (int dx, int dy);

void moveto (int x, int y);

void outtext (char *textstring);

void outtextxy (int x, int y, char *textstring);

void pieslice (int x, int y, int stangle, int endangle, int
radius);

void putimage (int left, int top, void *bitmap, int op);

void putpixel (int x, int y, int color);

void rectangle (int left, int top, int right, int bottom);

int registerbgidriver (void (*driver)(void));

int registerbgifont (void (*font)(void));

void registermousehandler (int kind, void h(int, int));

void restorecrtmode (void);

. int charsize).b). RGB macros: COLOR(r. int top. int yradius). void setpalette (int colornum. void setrgbpalette (int colornum. void setusercharsize (int multx. void setfillstyle (int pattern. int divy). IS_BGI_COLOR(v). void setgraphmode (int mode). int bottom. int blue). int clip). RED_VALUE(v). void setwritemodesetwritemode(int mode). int multy. void setlinestyle (int linestyle. int textheight (char *textstring). int vert). int stangle. int right. void setallpalette (struct palettetype *palette). void settextstyle (int font. BLUE_VALUE(v). void setbkcolor (int color). int textwidth (char *textstring). int xradius. unsigned upattern. int endangle. void setcolor (int color). void settextjustify (int horiz. unsigned setgraphbufsize (unsigned bufsize). void setfillpattern (char *upattern. int red. void setviewport (int left. IS_RGB_COLOR(v) void sector (int x. int color). int color). void setactivepage (int page). int yasp). void setvisualpage (int page). GREEN_VALUE(v). int green.g. int direction. int color). int divx. void setaspectratio (int xasp. int thickness). int y.

int radius). ""). If you are using a CGA in high resolution mode or a monochrome graphics adapter.y) with a radius given by radius. int radius = 100. the call to arc draws a complete circle. circles. Only the thickness parameter is used. pass the value 1 to those functions that alter the fill or drawing color (setcolor.arc Syntax #include <graphics. int midx. The angle for arc is reckoned counterclockwise. if (errorcode != grOk) { /* an error occurred */ . Description arc draws a circular arc in the current drawing color centered at (x. The arc travels from stangle to endangle.h> int main(void) { /* request autodetection */ int gdriver = DETECT.h> #include <conio. int y.h).h> void arc(int x. instead of a symbolic color constant (defined in graphics.h> #include <stdio. int endangle. or pie slices. The linestyle parameter does not affect arcs. ellipses. gmode. 90 degrees at 12 o'clock. /* initialize graphics and local variables */ initgraph(&gdriver. &gmode. for example). int stangle = 45. and setlinestyle. with 0 degrees at 3 o'clock. int stangle. If stangle equals 0 and endangle equals 360. the examples in online Help that show how to use graphics functions might not produce the expected results. See also circle ellipse fillellipse getarcoords getaspectratio pieslice sector Example /* arc example */ #include <graphics. Return Value None. /* read result of initialization */ errorcode = graphresult(). endangle = 135. and so on. midy. errorcode. setfillstyle.h> #include <stdlib. If your system runs on a CGA or monochrome adapter.

setcolor(getmaxcolor()).h> #include <stdio. rectangular.h> #include <conio. bottom). return 0. exit(1).h> void bar(int left. Return Value None.h> #include <stdlib. radius). The bar is filled using the current fill pattern and fill color. midy = getmaxy() / 2. printf("Graphics error: %s\n". endangle. int right. i. midy. use bar3d with depth equal to 0. closegraph(). midy. respectively. to draw an outlined two- dimensional bar. grapherrormsg(errorcode)). The upper left and lower right corners of the rectangle are given by (left.h> int main(void) { /* request autodetection */ int gdriver = DETECT. } bar Syntax #include <graphics. bar does not outline the bar. /* terminate with an error code */ } midx = getmaxx() / 2. getch(). two-dimensional bar. stangle. /* draw arc */ arc(midx. /* initialize graphics and local variables */ . See also bar3d rectangle setcolor setfillstyle setlinestyle Example /* bar example */ #include <graphics. gmode. int bottom). The coordinates refer to pixels. top) and (right. /* clean up */ getch(). int top. Description bar draws a filled-in. int midx. errorcode. printf("Press any key to halt:").

i<USER_FILL.right. like this: bar3d(left. int depth. initgraph(&gdriver. (right-left)/4. i++) { /* set the fill style */ setfillstyle(i. The upper left and lower right corners of the rectangle are given by (left. midy = getmaxy() / 2. The bar's depth in pixels is given by depth. midy-50. midx+50. Return Value None. bottom). int topflag). /* read result of initialization */ errorcode = graphresult(). printf("Press any key to halt:"). See also bar rectangle setcolor setfillstyle setlinestyle . respectively. To calculate a typical depth for bar3d. } /* clean up */ closegraph(). /* terminate with an error code */ } midx = getmaxx() / 2.top. The three-dimensional outline of the bar is drawn in the current line style and color. grapherrormsg(errorcode)). return 0. getch(). if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". int top. /* draw the bar */ bar(midx-50. /* loop through the fill patterns */ for (i=SOLID_FILL. top) and (right. getmaxcolor()).1). int bottom.bottom. midy+50). exit(1). int right. then fills it using the current fill pattern and fill color. } bar3d Syntax #include <graphics. &gmode. no top is put on the bar (making it possible to stack several bars on top of one another). otherwise. If topflag is nonzero.h> void bar3d(int left. getch(). The topflag parameter governs whether a three-dimensional top is put on the bar. take 25% of the width of the bar. Description bar3d draws a three-dimensional rectangular bar. ""). a top is put on.

midx+50. midy+50. ellipses. int radius). or pie slices. /* read result of initialization */ errorcode = graphresult(). printf("Press any key to halt:"). getmaxcolor()).y) and the radius given by radius. if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". } circle Syntax #include <graphics. The linestyle parameter does not affect arcs. circles.h> int main(void) { /* request autodetection */ int gdriver = DETECT. 10. /* loop through the fill patterns */ for (i=EMPTY_FILL. int midx. i. i++) { /* set the fill style */ setfillstyle(i. midy. int y. &gmode.h> void circle(int x. return 0.h> #include <stdlib. ""). /* draw the 3-d bar */ bar3d(midx-50. . midy = getmaxy() / 2. grapherrormsg(errorcode)). /* terminate with an error code */ } midx = getmaxx() / 2. midy-50. } /* clean up */ closegraph(). getch(). i<USER_FILL. getch().h> #include <stdio. Description circle draws a circle in the current drawing color with its center at (x. /* initialize graphics and local variables */ initgraph(&gdriver. 1). Only the thickness parameter is used. gmode.h> #include <conio.Example /* bar3d example */ #include <graphics. errorcode. exit(1).

/* read result of initialization */ errorcode = graphresult(). radius). gmode. midy = getmaxy() / 2.h> #include <stdlib. int midx. /* initialize graphics and local variables */ initgraph(&gdriver. /* terminate with an error code */ } midx = getmaxx() / 2. /* clean up */ getch(). adjust the aspect ratio. closegraph(). Return Value None. exit(1). } cleardevice Syntax #include >graphics.h> int main(void) { /* request autodetection */ int gdriver = DETECT. getch().h< . midy. setcolor(getmaxcolor()). See also arc ellipse fillellipse getaspectratio sector setaspectratio Example /* circle example */ #include <graphics.h> #include <stdio. If your circles are not perfectly round. return 0. /* draw the circle */ circle(midx.h> #include <conio. errorcode. printf("Press any key to halt:"). ""). if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". radius = 100. &gmode. midy. grapherrormsg(errorcode)).

Description cleardevice erases (that is. if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n".0). midy. ""). /* for centering screen messages */ settextjustify(CENTER_TEXT. /* terminate with an error code */ } midx = getmaxx() / 2. grapherrormsg(errorcode)). midy. CENTER_TEXT).h> #include <stdlib. void cleardevice(void). int midx. Return Value None. errorcode. midy = getmaxy() / 2. fills with the current background color) the entire graphics screen and moves the CP (current position) to home (0. /* read result of initialization */ errorcode = graphresult(). /* clear the screen */ /* output another message */ outtextxy(midx. /* clean up */ getch(). /* output a message to the screen */ outtextxy(midx. "Press any key to quit:"). closegraph(). printf("Press any key to halt:").h> #include <stdio. gmode. getch(). getch().h> int main(void) { /* request autodetection */ int gdriver = DETECT. midy. } . setcolor(getmaxcolor()). exit(1). "Press any key to clear the screen:"). /* wait for a key */ cleardevice(). See also clearviewport Example /* cleardevice example */ #include <graphics. /* initialize graphics and local variables */ initgraph(&gdriver.h> #include <conio. &gmode. return 0.

300).detect when the right mouse button is released up The middle mouse button handlers aren't working on my machine. int maxx.detect when the right mouse button is double clicked WM_RBUTTONDOWN .clearmouseclick Syntax #include "winbgim..detect when the middle mouse button is released up WM_RBUTTONDBLCLK .detect when the left mouse button is clicked down WM_LBUTTONUP ..h" void main(void) { const int LIMIT = 10. After calling getmouseclick.detect when the middle mouse button is double clicked WM_MBUTTONDOWN . I haven't yet tracked down the reason--it could be a broken mouse or it could be a bug in my programming.detect when the left mouse button is released up WM_MBUTTONDBLCLK .. the ismouseclick will return false for that kind of event until another such event occurs. Description The clearmouseclick function is available in the winbgim implementation of BGI graphics.detect when the middle mouse button is clicked down WM_MBUTTONUP . .. This is just like getmouseclick....... for a particular kind of event. // Number of clicks to stop program.. except it does not provide the x and y coordinates of the event.. // Maximum x and y pixel coordinates int count = 0. See also ismouseclick getmouseclick Example /* mouse example */ #include "winbgim.. // Divisor for the length of a triangle side // Put the machine into graphics mode and get the maximum coordinates: initwindow(450.h file: WM_MOUSEMOVE if you want to detect a mouse movement WM_LBUTTONDBLCLK . The value of the argument kind may be any of the constants listed above. The kind argument to clearmouseclick is one of these constants from the winbgim.. maxy. maxx = getmaxx( ).detect when the right mouse button is clicked down WM_RBUTTONUP ... // Number of mouse clicks int divisor.h" void clearmouseclick(int kind)...detect when the left mouse button is double clicked WM_LBUTTONDOWN .

maxy = getmaxy( );

// Draw a white circle with red inside and a radius of 50 pixels:
setfillstyle(SOLID_FILL, RED);
setcolor(WHITE);
fillellipse(maxx/2, maxy/2, 50, 50);

// Print a message and wait for a red pixel to be double clicked:
settextstyle(DEFAULT_FONT, HORIZ_DIR, 2);
outtextxy(20, 20, "Left click " << LIMIT << " times to end.");
setcolor(BLUE);
divisor = 2;
while (count < LIMIT)
{
triangle(maxx/divisor, maxy/divisor);
delay(500);
divisor++;
if (ismouseclick(WM_LBUTTONDOWN))
{
clearmouseclick(WM_LBUTTONDOWN));
count++;
}
}

// Switch back to text mode:
closegraph( );
}

clearviewport
Syntax
#include <graphics.h>
void clearviewport(void);
Description
clearviewport erases the viewport and moves the CP (current position) to home (0,0),
relative to the viewport.
Return Value
None.
See also
cleardevice
getviewsettings
setviewport
Example
/* clearviewport example */

#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

#define CLIP_ON 1 /* activates clipping in viewport */

int main(void)
{
/* request autodetection */

int gdriver = DETECT, gmode, errorcode, ht;

/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");

/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));

printf("Press any key to halt:");
getch();
exit(1); /* terminate with an error code */
}

setcolor(getmaxcolor());
ht = textheight("W");

/* message in default full-screen viewport */
outtextxy(0, 0, "* <-- (0, 0) in default viewport");

/* create a smaller viewport */
setviewport(50, 50, getmaxx()-50, getmaxy()-50, CLIP_ON);

/* display some messages */
outtextxy(0, 0, "* <-- (0, 0) in smaller viewport");

outtextxy(0, 2*ht, "Press any key to clear viewport:");

getch(); /* wait for a key */
clearviewport(); /* clear the viewport */
/* output another message */
outtextxy(0, 0, "Press any key to quit:");

/* clean up */
getch();
closegraph();
return 0;
}

closegraph
Syntax
#include <graphics.h>
void closegraph(void);
Description
closegraph deallocates all memory allocated by the graphics system, then restores the
screen to the mode it was in before you called initgraph. (The graphics system
deallocates memory, such as the drivers, fonts, and an internal buffer, through a call to
_graphfreemem.)
Return Value
None.
See also
initgraph
setgraphbufsize

Example
/* closegraph example */

#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

int main(void)
{
/* request autodetection */
int gdriver = DETECT, gmode, errorcode, x, y;

/* initialize graphics mode */
initgraph(&gdriver, &gmode, "");

/* read result of initialization */
errorcode = graphresult();

if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");

getch();
exit(1); /* terminate with an error code */
}

x = getmaxx() / 2;
y = getmaxy() / 2;

/* output a message */
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(x, y, "Press a key to close the graphics system:");

getch(); /* wait for a key */
/* closes down the graphics system */
closegraph();
printf("We're now back in text mode.\n");
printf("Press any key to halt:");
getch();
return 0;

}

delay
Syntax
#include "winbgim.h"
void delay(int millisec);
Description
The delay function is available in the winbgim implementation of BGI graphics. You
do not need to include conio.h; just include winbgim.h. The function pauses the
computation for the the specified number of milliseconds.
Return Value
None.

Example /* delay example */ #include "winbgim. i++) { /* set the fill style */ setfillstyle(i. midx = getmaxx() / 2. i. midx+50. /* draw the bar */ bar(midx-50. int *graphmode). return 0. and graphresult returns grNotDetected (-2). *graphdriver is an integer that specifies the graphics driver to be used.See also None. /* initialize the window size */ initwindow(100.h and listed as follows: graphics_drivers constant Numeric value DETECT 0 (requests autodetect) CGA 1 MCGA 2 EGA 3 EGA64 4 . 100).h" int main(void) { int midx. midy+50). } detectgraph Syntax #include <graphics. i<USER_FILL. midy = getmaxy() / 2. You can give it a value using a constant of the graphics_drivers enumeration type defined in graphics. If no graphics hardware is detected. } /* clean up */ closegraph(). getmaxcolor()).h> void detectgraph(int *graphdriver. delay(4000). Description detectgraph detects your system's graphics adapter and chooses the mode that provides the highest resolution for that adapter. /* loop through the fill patterns with 4 second delays */ for (i=SOLID_FILL. midy-50. midy. *graphdriver is set to grNotDetected (-2).

Columns Graphics Driver graphics_mode Value x Rows Palette Pages CGA CGAC0 0 320 x 200 C0 1 CGAC1 1 320 x 200 C1 1 CGAC2 2 320 x 200 C2 1 CGAC3 3 320 x 200 C3 1 CGAHI 4 640 x 200 2 color 1 MCGA MCGAC0 0 320 x 200 C0 1 MCGAC1 1 320 x 200 C1 1 MCGAC2 2 320 x 200 C2 1 MCGAC3 3 320 x 200 C3 1 MCGAMED 4 640 x 200 2 color 1 MCGAHI 5 640 x 480 2 color 1 EGA EGALO 0 640 x 200 16 color 4 EGAHI 1 640 x 350 16 color 2 EGA64 EGA64LO 0 640 x 200 16 color 1 EGA64HI 1 640 x 350 4 color 1 EGA-MONO EGAMONOHI 3 640 x 350 2 color 1 w/64K EGAMONOHI 3 640 x 350 2 color 2 w/256K HERC HERCMONOHI 0 720 x 348 2 color 2 ATT400 ATT400C0 0 320 x 200 C0 1 ATT400C1 1 320 x 200 C1 1 . You can give *graphmode a value using a constant of the graphics_modes enumeration type defined in graphics. *graphmode is set to the highest resolution available for the detected driver).h and listed as follows. in which case.EGAMONO 5 IBM8514 6 HERCMONO 7 ATT400 8 VGA 9 PC3270 10 *graphmode is an integer that specifies the initial graphics mode (unless *graphdriver equals DETECT.

gmode. "a 64K EGA". errorcode. "a VGA". Return Value None.h> #include <conio. "an IBM 8514".h> #include <stdlib. regardless of the machine's hardware. See also graphresult initgraph Example /* detectgraph example */ #include <graphics. Windows Notes The winbgim version of detectgraph returns VGA for the graphdriver and VGAHI for the graphmode. ATT400C2 2 320 x 200 C2 1 ATT400C3 3 320 x 200 C3 1 ATT400MED 4 640 x 200 2 color 1 ATT400HI 5 640 x 400 2 color 1 VGA VGALO 0 640 x 200 16 color 2 VGAMED 1 640 x 350 16 color 2 VGAHI 2 640 x 480 16 color 1 PC3270 PC3270HI 0 720 x 350 2 color 1 IBM8514 IBM8514HI 0 640 x 480 256 color ? IBM8514LO 0 1024 x 768 256 color ? Note: The main reason to call detectgraph directly is to override the graphics mode that detectgraph recommends to initgraph. int main(void) { /* used to return detected hardware info. "a monochrome EGA". "an EGA". "an MCGA". . "an AT&T 6300 PC".h> #include <stdio. "a Hercules monochrome". However. the screen is not necessarily 640 x 480.h> /* the names of the various cards supported */ char *dname[] = { "requests detection". "a CGA". */ int gdriver. "an IBM 3270 PC" }.

h> int main(void) { /* request autodetection */ int gdriver = DETECT. gmode. maxy. } drawpoly Syntax #include <graphics. /* read result of detectgraph call */ errorcode = graphresult(). *polypoints points to a sequence of (numpoints * 2) integers.and y-coordinates of a point on the polygon. errorcode. using the current line style and color. exit(1). Description drawpoly draws a polygon with numpoints points. int maxx.\n". you must pass n + 1 coordinates to drawpoly where the nth coordinate is equal to the 0th. getch(). getch().h> #include <stdlib. dname[gdriver]). Each pair of integers gives the x. Return Value None. . &gmode). if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". See also fillpoly floodfill graphresult setwritemode Example /* drawpoly example */ #include <graphics. printf("Press any key to halt:"). /* terminate with an error code */ } /* display the information detected */ clrscr(). return 0. /* detect the graphics hardware available */ detectgraph(&gdriver.h> #include <stdio.h> void drawpoly(int numpoints. printf("Press any key to halt:").h> #include <conio. printf("You have %s video display card. grapherrormsg(errorcode)). int *polypoints). In order to draw a closed figure with n vertices.

closegraph(). /* third vertex */ poly[5] = maxy . int y. /* fourth vertex */ poly[7] = maxy / 2. poly[0] = 20. getch(). /* the polygon. The ellipse travels from stangle to endangle. int poly[10]. &gmode.20. printf("Press any key to halt:"). ""). 90 degrees at 12 o'clock. int stangle. Only the thickness parameter is used. if (errorcode != grOk){ /* an error occurred */ printf("Graphics error: %s\n". int endangle. exit(1). the call to ellipse draws a complete ellipse. The angle for ellipse is reckoned counterclockwise. respectively. poly[4] = maxx . maxy = getmaxy(). or pie slices. If stangle equals 0 and endangle equals 360. /* drawpoly doesn't automatically close */ poly[9] = poly[1]. poly[6] = maxx / 2. grapherrormsg(errorcode)). poly[8] = poly[0]. poly[2] = maxx . Return Value None.h> void ellipse(int x.y) and the horizontal and vertical axes given by xradius and yradius. /* terminate with an error code */ } maxx = getmaxx(). /* our polygon array */ /* initialize graphics and local variables */ initgraph(&gdriver. return 0. ellipses. so we close it */ drawpoly(5.50. } ellipse Syntax #include <graphics. /* second vertex */ poly[3] = 20. /* read result of initialization */ errorcode = graphresult(). /* draw the polygon */ /* clean up */ getch(). and so on. The linestyle parameter does not affect arcs.20. int yradius). with 0 degrees at 3 o'clock. poly). int xradius. /* first vertex */ poly[1] = maxy / 2. Description ellipse draws an elliptical arc in the current drawing color with its center at (x. . circles.

See also arc circle fillellipse sector Example /* ellipse example */ #include <graphics. midy = getmaxy() / 2. getch(). } fillellipse Syntax #include <graphics. closegraph(). and fills it with the current fill color and fill pattern. return 0. Description Draws an ellipse using (x. /* read result of initialization */ errorcode = graphresult().y) as a center point and xradius and yradius as the horizontal and vertical axes. /* draw ellipse */ ellipse(midx. printf("Press any key to halt:"). .h> int main(void) { /* request autodetection */ int gdriver = DETECT. /* terminate with an error code */ } midx = getmaxx() / 2. int stangle = 0.h> #include <stdlib. midy. grapherrormsg(errorcode)). exit(1). &gmode.h> #include <conio. ""). int xradius. endangle = 360. int yradius). endangle. midy. int xradius = 100.h> #include <stdio. stangle. xradius. int y. yradius = 50. if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". int midx. /* clean up */ getch(). setcolor(getmaxcolor()).h> void fillellipse(int x. errorcode. gmode. yradius). /* initialize graphics and local variables */ initgraph(&gdriver.

/* draw a filled ellipse */ fillellipse(midx. if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". errorcode. } /* clean up */ closegraph(). /* read result of initialization */ errorcode = graphresult(). exit(1). } fillpoly . midy = getmaxy() / 2. See also arc circle ellipse pieslice Example /* fillellipse example */ #include <graphics. i. getch(). getch(). xradius.Return Value None. getmaxcolor()). i < USER_FILL. printf("Press any key to halt:"). /* terminate with an error code */ } midx = getmaxx() / 2. yradius = 50.h> #include <stdio. ""). /* initialize graphics and local variables */ initgraph(&gdriver. midy. yradius).h> #include <conio. /* loop through the fill patterns */ for (i = EMPTY_FILL. midy. return 0. grapherrormsg(errorcode)). gmode.h> int main(void) { /* request autodetection */ int gdriver = DETECT. &gmode. i++) { /* set fill pattern */ setfillstyle(i.h> #include <stdlib. int midx. int xradius = 100.

Each pair of integers gives the x. poly[4] = maxx .h> int main(void) { /* request autodetection */ int gdriver = DETECT. /* fourth. polypoints points to a sequence of (numpoints * 2) integers. getch(). /* our polygon array */ int poly[8].20. grapherrormsg(errorcode)). See also drawpoly floodfill graphresult setfillstyle Example /* fillpoly example */ #include <graphics.h> #include <conio. int i. if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". poly[0] = 20. /* read result of initialization */ errorcode = graphresult(). 20.h> #include <stdio. /* third vertex */ poly[5] = maxy . /* initialize graphics and local variables */ initgraph(&gdriver. exit(1). gmode. "").h> #include <stdlib. /* second vertex */ poly[3] = 20. /* first vertex */ poly[1] = maxy / 2. 50. int *polypoints). poly[2] = maxx . maxy.Syntax #include <graphics.and y-coordinates of a point on the polygon. printf("Press any key to halt:"). maxx. maxy = getmaxy(). then fills the polygon using the current fill pattern and fill color. /* closes the polygon */ . &gmode. errorcode. fillpoly automatically */ poly[7] = maxy / 2. Description fillpoly draws the outline of a polygon with numpoints points in the current line style and color (just as drawpoly does). /* terminate with an error code */ } maxx = getmaxx().h> void fillpoly(int numpoints. Return Value None. poly[6] = maxx / 2.

y) is a "seed point" within the enclosed area to be filled. errorcode. poly). int y. } floodfill Syntax #include <graphics.h> int main(void) { /* request autodetection */ int gdriver = DETECT. the inside will be filled. /* draw a filled polygon */ fillpoly(4. Return Value If an error occurs while flooding a region.h> #include <conio. If the seed is outside the enclosed area.h> #include <stdlib. floodfill does not work with the IBM-8514 driver. The area bounded by the color border is flooded with the current fill pattern and fill color. the exterior will be filled. Use fillpoly instead of floodfill whenever possible so that you can maintain code compatibility with future versions. Description floodfill fills an enclosed area on bitmap devices.h> #include <stdio. Windows Notes The winbgim version allows the border argument to be an ordinary BGI color (from 0 to 15) or an RGB color. gmode. graphresult returns a value of -7. See also drawpoly fillpoly graphresult setcolor setfillstyle Example /* floodfill example */ #include <graphics. i<USER_FILL. } /* clean up */ closegraph(). getmaxcolor()). i++) { /* set fill pattern */ setfillstyle(i. (x. /* loop through the fill patterns */ for (i=EMPTY_FILL. int border). . If the seed point is within an enclosed area. getch().h> void floodfill(int x. return 0.

/* clean up */ getch(). grapherrormsg(errorcode)). maxy). /* select drawing color */ setcolor(getmaxcolor()). getmaxcolor()). 25). maxy-20. } getactivepage Syntax #include "winbgim. maxy = getmaxy(). getmaxcolor()). 0. /* fill in bounded region */ floodfill(2. maxy /2. 75). printf("Press any key to halt:"). circle(maxx / 2. &gmode. 50). 2. 20. getch(). exit(1). int maxx. maxy-50. ""). maxx.h" int getactivepage(void). Description . if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". /* terminate with an error code */ } maxx = getmaxx(). 100). /* draw some circles */ circle(maxx / 3. /* select fill color */ setfillstyle(SOLID_FILL. return 0. circle(maxx-20. maxy. closegraph(). /* read result of initialization */ errorcode = graphresult(). /* draw a border around the screen */ rectangle(0. /* initialize graphics and local variables */ initgraph(&gdriver. circle(20. /* wait for a key */ getch().

The getactivepage function is available in the winbgim implementation of BGI graphics.h> #include <conio. }. Return Value None. char sstr[80]. The arccoordstype structure is defined in graphics. I use pages 1-2 for double buffering. ystart). See also arc fillellipse sector Example /* getarccoords example */ #include <graphics. errorcode. yend) of the arc. depending on how many graphics pages are available on your system. and the ending position (xend.h> #include <stdlib. The active graphics page might not be the one you see onscreen. int midx.h> #include <stdio. The members of this structure are used to specify the center point (x. int xstart. struct arccoordstype arcinfo. xend. int stangle = 45. Return Value The page number of the currently active page. y. the starting position (xstart. Description getarccoords fills in the arccoordstype structure pointed to by arccoords with information about the last call to arc.h as follows: struct arccoordstype { int x.y). midy. but I have only used pages 1 and 2 myself. gmode. The original winbgi was designed to support up to 16 pages. estr[80].h> int main(void) { /* request autodetection */ int gdriver = DETECT. yend. .h> void getarccoords(struct arccoordstype *arccoords). NOTE: Using page number 0 might mess up the colors. endangle = 270. ystart. getarccoords Syntax #include <graphics. These values are useful if you need to make a line meet at the end of an arc. getactivepage gets the page number of the currently active page (where drawing takes place).

arcinfo. exit(1). is normalized to 10. . endangle. estr). "*. *yasp. which has "square" pixels. Description The y aspect factor. %d)".(%d.000 *xasp <= 10.xstart. midy = getmaxy() / 2. arcinfo. /* convert arc information into strings */ sprintf(sstr.xstart.ystart).000. midy. stangle. /* initialize graphics and local variables */ initgraph(&gdriver. On the VGA. arcinfo. /* clean up */ getch(). arcinfo. /* read result of initialization */ errorcode = graphresult().(%d.ystart. printf("Press any key to halt:"). On all graphics adapters except the VGA.xend. outtextxy(arcinfo.h> void getaspectratio(int *xasp. return 0.000 getaspectratio gets the values in *xasp and *yasp. ""). getarccoords(&arcinfo). closegraph(). the relationship between *yasp and *xasp can be stated as *yasp = 10. arcinfo. See also None. "*. if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n".yend. %d)". In general. *xasp equals *yasp. } getaspectration Syntax #include <graphics.yend). grapherrormsg(errorcode)). sstr). arc(midx. &gmode. sprintf(estr. /* terminate with an error code */ } midx = getmaxx() / 2. 100). /* output the arc information */ outtextxy(arcinfo. getch(). /* draw arc and get coordinates */ setcolor(getmaxcolor()). Return Value None. *xasp (the x aspect factor) is less than *yasp because the pixels are taller than they are wide. int *yasp).xend. arcinfo.

/* terminate with an error code */ } midx = getmaxx() / 2. midy. /* draw wide circle */ cleardevice(). setcolor(getmaxcolor()). /* read result of initialization */ errorcode = graphresult(). /* draw normal circle */ circle(midx. getch(). &yasp). yasp. return 0. closegraph(). circle(midx.h> #include <stdio. grapherrormsg(errorcode)).h> #include <conio. errorcode. gmode. printf("Press any key to halt:"). getch(). 100). midy. midx. midy. 100). 100). } getbkcolor . yasp/2). yasp). setaspectratio(xasp/2. /* initialize graphics and local variables */ initgraph(&gdriver. int xasp. /* clean up */ getch(). &gmode. circle(midx. /* draw narrow circle */ cleardevice(). exit(1). ""). setaspectratio(xasp.Example /* getaspectratio example */ #include <graphics. if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". getch(). /* get current aspect ratio settings */ getaspectratio(&xasp. midy = getmaxy() / 2.h> main() { /* request autodetection */ int gdriver = DETECT.h> #include <stdlib. midy.

h> #include <stdlib.h> #include <string. ""). midy = getmaxy() / 2. See also getcolor getmaxcolor getpalette setbkcolor Example /* getbkcolor example */ #include <graphics. the return value from getbkcolor might be an ordinary BGI color (integer from 0 to 15) or an RGB color.Syntax #include <graphics. gmode.h> #include <stdio. &gmode. the user might set the background color to an RGB color.h> int getbkcolor(void). /* initialize graphics and local variables */ initgraph(&gdriver. /* terminate with an error code */ } midx = getmaxx() / 2. /* convert color value into a string */ . if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". setcolor(getmaxcolor()). midy. midx. char bkname[35]. Windows Notes In the winbgim version. errorcode.h> int main(void) { /* request autodetection */ int gdriver = DETECT. printf("Press any key to halt:"). Description getbkcolor returns the current background color. grapherrormsg(errorcode)). getch(). /* for centering text on the display */ settextjustify(CENTER_TEXT. Therefore. int bkcolor. exit(1).h> #include <conio. CENTER_TEXT). /* get the current background color */ bkcolor = getbkcolor().) Return Value getbkcolor returns the current background color. (See the table in setbkcolor for details. /* read result of initialization */ errorcode = graphresult().

10). bkname. closegraph(). the getch function first returns ASCII 0.h. You do not need to include conio. the user must click in the graphics window (i. Description The getch function is available in the winbgim implementation of BGI graphics. the Windows focus must be in the graphics window). itoa(bkcolor.").h> // Provides cout .h" int getch(void).h> // Provides sprintf #include <iostream. For special keys.e. strcat(bkname. The next call will then return one of these special keys: #define KEY_HOME 71 #define KEY_UP 72 #define KEY_PGUP 73 #define KEY_LEFT 75 #define KEY_CENTER 76 #define KEY_RIGHT 77 #define KEY_END 79 #define KEY_DOWN 80 #define KEY_PGDN 81 #define KEY_INSERT 82 #define KEY_DELETE 83 #define KEY_F1 59 #define KEY_F2 60 #define KEY_F3 61 #define KEY_F4 62 #define KEY_F5 63 #define KEY_F6 64 #define KEY_F7 65 #define KEY_F8 66 #define KEY_F9 67 Return Value The ASCII value of a key that has been pressed. See also kbhit Example #include "winbgim. In order to work..h" #include <stdio. midy. " is the current background color. bkname). just include winbgim. /* display a message */ outtextxy(midx. The function reads one character from the keyboard and returns its ASCII value (without waiting for a return key). } getch Syntax #include "winbgim. /* clean up */ getch(). return 0.h.

")." << endl. case KEY_CENTER: cout << "Center key." << endl. break. case KEY_END: cout << "End key. // Convert some numbers to strings and draw them in graphics window: outtextxy(10. "and then press arrow keys. case KEY_LEFT: cout << "Left key. case KEY_F1: cout << "F1 key. 150. case KEY_INSERT: cout << "Insert key. 10. int value)." << endl. else { // Process one of the special keys: c = (char) getch( ). ." << endl. "Press X to exit. "Click in this graphics window. 300). case KEY_RIGHT: cout << "Right key. int y." << endl. break. i <= 100. break. for (i = 10. break. // Get some characters from the keyboard until an X is typed: outtextxy(20." << endl." << endl. case KEY_UP: cout << "Up key. break. int main( ) { int i. outtextxy(20. case KEY_PGUP: cout << "PgUp key. i+10." << endl. break. if (c != 0) cout << "That is ASCII value: " << (int) c << endl."). break. break. 130. i). i += 10) outintxy(20. outtextxy(20. // Initialize the graphics window.void outintxy(int x. "Here are some numbers:")." << endl."). break. break. break." << endl.")." << endl. "Watch the console window while pressing. case KEY_F2: cout << "F2 key. break. switch (c) { case KEY_HOME: cout << "Home key. char c. case KEY_DELETE: cout << "Delete key. outtextxy(20. 160. case KEY_PGDN: cout << "PgDn key. 140." << endl. case KEY_DOWN: cout << "Down key. init_window(400." << endl. break. do { c = (char) getch( )." << endl. break. case KEY_F3: cout << "F3 key.

" << endl. sprintf(digit_string." << endl. in CGAC0 mode. light green. outtextxy(x.h> #include <string." << endl. Windows Notes In the winbgim version. light red." << endl. the return value from getcolor might be an ordinary BGI color (integer from 0 to 15) or an RGB color. } void outintxy(int x. break. value). Return Value getcolor returns the current drawing color. break.h> int getcolor(void). y." << endl. case KEY_F7: cout << "F7 key. closegraph( ). the current drawing color is light green. Description getcolor returns the current drawing color. int value) { char digit_string[20]. See also getbkcolor getmaxcolor getpalette setcolor Example /* getcolor example */ #include <graphics. digit_string). default: cout << "Unknown extended key. case KEY_F6: cout << "F6 key. case KEY_F9: cout << "F9 key. the user might set the drawing color to an RGB color. break. case KEY_F5: cout << "F5 key." << endl. break. case KEY_F8: cout << "F8 key. In this mode.h> #include <stdlib. the palette contains four colors: the background color. Therefore. break. "%d". The drawing color is the value to which pixels are set when lines and so on are drawn. } } } while ((c != 'x') && (c != 'X')). For example. } getcolor Syntax #include <graphics. and yellow. if getcolor returns 1.h> ." << endl. case KEY_F4: cout << "F4 key. break. int y.

return 0. exit(1). errorcode. if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". " is the current drawing color.h> #include <conio. setcolor(getmaxcolor()). /* initialize graphics and local variables */ initgraph(&gdriver. colname). /* read result of initialization */ errorcode = graphresult(). ""). /* get the current drawing color */ color = getcolor(). char colname[35]. midy = getmaxy() / 2. /* for centering text on the display */ settextjustify(CENTER_TEXT. gmode. colname.h> int main(void) { /* request autodetection */ int gdriver = DETECT. 10). &gmode."). Description getdefaultpalette finds the palettetype structure that contains the palette initialized by the driver during initgraph. int color. CENTER_TEXT). midy. /* terminate with an error code */ } midx = getmaxx() / 2. printf("Press any key to halt:"). /* clean up */ getch(). closegraph(). midy. } getdefaultpalette Syntax #include <graphics. . midx. /* convert color value into a string */ itoa(color. getch(). strcat(colname. #include <stdio. grapherrormsg(errorcode)). /* display a message */ outtextxy(midx.h> struct palettetype *getdefaultpalette(void).

h> int main(void) { /* request autodetection */ int gdriver = DETECT. i++) { printf("colors[%d] = %d\n". pal->colors[i]). grapherrormsg(errorcode)). /* terminate with an error code */ } /* return a pointer to the default palette */ pal = getdefaultpalette(). See also getpalette initgraph Example /* getdefaultpalette example */ #include <graphics.h> #include <stdio. return 0. } getdrivername Syntax #include <graphics. closegraph(). /* initialize graphics and local variables */ initgraph(&gdriver. int i. gmode.h> #include <stdlib. printf("Press any key to halt:"). /* pointer to palette structure */ struct palettetype *pal = NULL. i. exit(1). getch(). getch(). for (i=0. /* read result of initialization */ errorcode = graphresult().h> #include <conio. ""). } /* clean up */ getch().Return Value getdefaultpalette returns a pointer to the default palette set up by the current driver when that driver was initialized. if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". i<pal->size.h> . &gmode. errorcode.

return 0. &gmode.h> int main() { /* request autodetection */ int gdriver = DETECT. } . grapherrormsg(errorcode)). printf("Press any key to halt:"). Windows Notes The winbgim version of getdrivername returns "EGAVGA" for the driver name. See also initgraph Example /* getdrivername example */ #include <graphics. CENTER_TEXT). Description After a call to initgraph. /* clean up */ getch(). ""). /* stores the device driver name */ char *drivername. regardless of how initgraph was called. char *getdrivername(void).h> #include <stdio. if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". exit(1). /* get the name of the device driver in use */ drivername = getdrivername(). closegraph().h> #include <stdlib. drivername). /* output the name of the driver */ outtextxy(getmaxx() / 2. /* for centering text onscreen */ settextjustify(CENTER_TEXT. getch(). errorcode. getmaxy() / 2. /* initialize graphics and local variables */ initgraph(&gdriver.h> #include <conio. /* read result of initialization */ errorcode = graphresult(). /* terminate with an error code */ } setcolor(getmaxcolor()). Return Value getdrivername returns a pointer to a string with the name of the currently loaded graphics driver. getdrivername returns the name of the driver that is currently loaded. gmode.

the following user-defined fill pattern represents a checkerboard: char checkboard[8] = { 0xAA. /* clean up */ getch(). 0x55. &gmode. maxx.h> void getfillsettings(struct fillsettingstype *fillinfo). Whenever a bit in a pattern byte is set to 1. if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". 0.h> void getfillpattern(char *pattern). pattern is a pointer to a sequence of 8 bytes. into the 8-byte area pointed to by pattern. errorcode. pattern[7] -= 4. For example. as set by setfillpattern. /* fill the screen with the pattern */ bar(0. getch(). char pattern[8] = {0x00. maxy).h> #include <conio. 0x04. maxy = getmaxy(). /* select a user-defined fill pattern */ setfillpattern(pattern. return 0.h> #include <stdio. printf("Press any key to halt:").getfillpattern Syntax #include <graphics. 0xAA. maxy). /* read result of initialization */ errorcode = graphresult(). /* alter the pattern we grabbed */ pattern[4] -= 1. /* fill the screen with the new pattern */ bar(0. with each byte corresponding to 8 pixels in the pattern. getmaxcolor()). int maxx. 0x55. setcolor(getmaxcolor()). maxy. Description getfillpattern copies the user-defined fill pattern. maxx. ""). exit(1). /* select our new pattern */ setfillpattern(pattern. closegraph(). the corresponding pixel will be plotted. 0x20.h> #include <stdlib. 0x70. /* initialize graphics and local variables */ initgraph(&gdriver. pattern[6] += 3.h> int main(void) { /* request autodetection */ int gdriver = DETECT. Description . pattern[5] -= 3. getmaxcolor()). /* get the current user-defined fill pattern */ getfillpattern(pattern). grapherrormsg(errorcode)). getch(). 0xAA. 0x27. /* terminate with an error code */ } maxx = getmaxx(). 0x27. gmode. 0. 0x55. 0xAA. 0x55 }. Return Value None. 0x04}. 0x25. } getfillsettings Syntax #include <graphics. See also getfillsettings setfillpattern Example /* getfillpattern example */ #include <graphics.

bar3d. See also getfillpattern setfillpattern setfillstyle Example /* getfillsettings example */ #include #include #include #include /* the names of the fill styles supported */ char *fname[] = { "EMPTY_FILL". "LINE_FILL". then a user-defined fill pattern is being used. the user might set the fill color to an RGB color. /* current fill color */ }. "SLASH_FILL". crosshatch. Symbolic names for the predefined patterns are provided by the enumerated type fill_patterns in graphics. In addition. as shown here: Name Value Description EMPTY_FILL 0 Fill with background color SOLID_FILL 1 Solid fill LINE_FILL 2 Fill with --- LTSLASH_FILL 3 Fill with /// SLASH_FILL 4 Fill with ///. "LTSLASH_FILL". There are 11 predefined fill pattern styles (such as solid. and pieslice all fill an area with the current fill pattern in the current fill color. thick lines LTBKSLASH_FILL 6 Fill with \\\ HATCH_FILL 7 Light hatch fill XHATCH_FILL 8 Heavy crosshatch fill INTERLEAVE_FILL 9 Interleaving line fill WIDE_DOT_FILL 10 Widely spaced dot fill CLOSE_DOT_FILL 11 Closely spaced dot fill USER_FILL 12 User-defined fill pattern Note: All but EMPTY_FILL fill with the current fill color. the color in the fillsettingstype struct might be an ordinary BGI color (integer from 0 to 15) or an RGB color. "LTBKSLASH_FILL". EMPTY_FILL uses the current background color. Therefore. otherwise.h. Windows Notes In the winbgim version. /* current fill pattern */ int color. and so on). The fillsettingstype structure is defined in graphics. The functions bar. floodfill. If pattern equals 12 (USER_FILL). you can define your own fill pattern.h as follows: struct fillsettingstype { int pattern. thick lines BKSLASH_FILL 5 Fill with \\\. "BKSLASH_FILL". dotted. "SOLID_FILL". getfillsettings fills in the fillsettingstype structure pointed to by fillinfo with information about the current fill pattern and fill color. . pattern gives the number of a predefined pattern. fillpoly. Return Value None.

"HATCH_FILL", "XHATCH_FILL", "INTERLEAVE_FILL", "WIDE_DOT_FILL",
"CLOSE_DOT_FILL", "USER_FILL" };

int main(void)
{
/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
struct fillsettingstype fillinfo;

int midx, midy;
char patstr[40], colstr[40];

/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");

/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1); /* terminate with an error code */
}

midx = getmaxx() / 2;

midy = getmaxy() / 2;

/* get info about current fill pattern and color */
getfillsettings(&fillinfo);

/* convert fill information into strings */
sprintf(patstr, "%s is the fill style.", fname[fillinfo.pattern]);
sprintf(colstr, "%d is the fill color.", fillinfo.color);

/* display the information */
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy, patstr);
outtextxy(midx, midy+2*textheight("W"), colstr);

/* clean up */

getch();
closegraph();
return 0;
}

getgraphmode

Syntax
#include <graphics.h>
int getgraphmode(void);
Description
Your program must make a successful call to initgraph before calling getgraphmode.

The enumeration graphics_mode, defined in graphics.h, gives names for the
predefined graphics modes. For a table listing these enumeration values, refer to the
description for initgraph.
Return Value
getgraphmode returns the graphics mode set by initgraph or setgraphmode.
Windows Notes
The winbgim version of getgraphmode returns VGAHI for the graphmode, regardless
of how initgraph was called. However, the screen is not necessarily 640 x 480.
See also
getmoderange
initgraph
restorecrtmode
setgraphmode
Example
/* getgraphmode example */

#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

int main(void)
{
/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int midx, midy, mode;
char numname[80], modename[80];

/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");

/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));

printf("Press any key to halt:");
getch();
exit(1); /* terminate with an error code */
}

midx = getmaxx() / 2;
midy = getmaxy() / 2;

/* get mode number and name strings */
mode = getgraphmode();
sprintf(numname, "%d is the current mode number.", mode);
sprintf(modename, "%s is the current graphics mode.",
getmodename(mode));

/* display the information */
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy, numname);

outtextxy(midx, midy+2*textheight("W"), modename);

/* clean up */
getch();

closegraph();
return 0;
}

getimage

Syntax
#include <graphics.h>
void getimage(int left, int top, int right, int bottom, void
*bitmap);
Description
getimage copies an image from the screen to memory.
left, top, right, and bottom define the screen area to which the rectangle is copied.
bitmap points to the area in memory where the bit image is stored. The first two words
of this area are used for the width and height of the rectangle; the remainder holds the
image itself.
Return Value
None.
See also
getpixel
imagesize
putimage
Example
/* getimage example */

#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <alloc.h>

void save_screen(void *buf[4]);
void restore_screen(void *buf[4]);

int maxx, maxy;
int main(void)
{
int gdriver=DETECT, gmode, errorcode;
void *ptr[4];

/* autodetect the graphics driver and mode */
initgraph(&gdriver, &gmode, "");
errorcode = graphresult(); /* check for any errors */
if (errorcode != grOk) {
printf("Graphics error: %s\n", grapherrormsg(errorcode));

printf("Press any key to halt:");
getch();
exit(1);
}

block++) { putimage(0. buf[block]. save_screen(ptr). maxx.\n"). ystart = yend + 1. 0). buf[block]). maxx. ystart. for (block=0. printf("Error: not enough heap space in save_screen(). /* pause screen */ cleardevice(). yend += yincr + 1. for (block=0. maxx. 0. yend. } void save_screen(void *buf[4]) { unsigned size. /* get byte size of image */ size = imagesize(0. /* clear screen */ restore_screen(ptr). maxy = getmaxy(). maxy. /* save the current screen */ getch(). } } void restore_screen(void *buf[4]) { int ystart=0. yincr = (maxy+1) / 4. COPY_PUT). yend). block<=3. } getimage(0. block<=3. maxx. maxx = getmaxx(). /* pause screen */ closegraph(). line(0. yincr = (maxy+1) / 4. block. maxy). /* draw an image on the screen */ rectangle(0. yend = yincr. line(0. farfree(buf[block]). } } getlinesettings Syntax . ystart. yend. 0. block++) { if ((buf[block] = farmalloc(size)) == NULL) { closegraph(). yend += yincr + 1. maxx. maxy). int ystart=0. ystart = yend + 1. yend. return 0. yincr. /* restore the screen */ getch(). yincr. exit(1). block. yend = yincr. ystart.

int main(void) { /* request autodetection */ int gdriver = DETECT. The enumeration line_styles. linestyle specifies in which style subsequent lines will be drawn (such as solid. #include <graphics. }. unsigned upattern. midy. pattern. ""). centered. struct linesettingstype lineinfo. and thickness. errorcode. lpattern[80]. "USERBIT_LINE" }. dotted.h. See also setlinestyle Example /* getlinesettings example */ #include <graphics.h> #include <stdlib. gmode. char lstyle[80]. int thickness. lwidth[80].h> #include <stdio. "DOTTED_LINE". "CENTER_LINE". . Description getlinesettings fills a linesettingstype structure pointed to by lineinfo with information about the current line style. Name Value Description NORM_WIDTH 1 1 pixel wide THICK_WIDTH 3 3 pixels wide Return Value None.h as follows: struct linesettingstype { int linestyle. gives names to these operators: Name Value Description SOLID_LINE 0 Solid line DOTTED_LINE 1 Dotted line CENTER_LINE 2 Centered line DASHED_LINE 3 Dashed line USERBIT_LINE 4 User-defined line style thickness specifies whether the width of subsequent lines drawn will be normal or thick. "DASHED_LINE". defined in graphics. &gmode.h> /* the names of the line styles supported */ char *lname[] = { "SOLID_LINE".h> #include <conio. /* initialize graphics and local variables */ initgraph(&gdriver.h> void getlinesettings(struct linesettingstype *lineinfo). The linesettingstype structure is defined in graphics. int midx. dashed).

which means that any call to setcolor with a value from 0 to 15 is valid.h> int getmaxcolor(void). outtextxy(midx. grapherrormsg(errorcode)). the programmer may also use RGB colors. /* get information about current line settings */ getlinesettings(&lineinfo). /* display the information */ settextjustify(CENTER_TEXT. On a CGA in high-resolution mode or on a Hercules monochrome adapter. lwidth). getmaxcolor returns a value of 1.". in addition to the usual BGI colors (0 through 15). "%s is the line style. getch(). lineinfo. /* clean up */ getch().upattern). if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". Windows Notes The winbgim version of getmaxcolor returns 15 for the maximum color. outtextxy(midx. lpattern).linestyle]). on a 256K EGA. sprintf(lpattern. CENTER_TEXT). } getmaxcolor Syntax #include <graphics. /* terminate with an error code */ } midx = getmaxx() / 2. Return Value . midy+2*textheight("W"). outtextxy(midx. lineinfo. lstyle). closegraph().". sprintf(lwidth. lname[lineinfo. midy = getmaxy() / 2. getmaxcolor always returns 15. Description getmaxcolor returns the highest valid color value for the current graphics driver and mode that can be passed to setcolor. printf("Press any key to halt:"). /* convert line information into strings */ sprintf(lstyle. midy.thickness). For example. However. /* read result of initialization */ errorcode = graphresult(). return 0. "0x%X is the user-defined line pattern. "%d is the line thickness. exit(1). midy+4*textheight("W").".

/* clean up */ getch().h> #include <stdio. /* read result of initialization */ errorcode = graphresult(). getmaxcolor returns the highest available color value. midy.h> #include <conio.h> #include <stdlib. ""). gmode. int midx. getmaxcolor()). outtextxy(midx. char colstr[80]. /* initialize graphics and local variables */ initgraph(&gdriver.. and convert it to a string */ sprintf(colstr.%d". colstr). midy. getch(). &gmode. errorcode. } getmaxmode . grapherrormsg(errorcode)). printf("Press any key to halt:"). /* terminate with an error code */ } midx = getmaxx() / 2.h> int main(void) { /* request autodetection */ int gdriver = DETECT. exit(1). CENTER_TEXT). midy = getmaxy() / 2. /* grab the color info. /* display the information */ settextjustify(CENTER_TEXT. return 0. if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". closegraph(). "This mode supports colors 0. See also getbkcolor getcolor getpalette getpalettesize setcolor Example /* getmaxcolor example */ #include <graphics.

/* display the information */ settextjustify(CENTER_TEXT. See also getmodename getmiderange Example /* getmaxmode example */ #include <graphics. This gives it an advantage over getmoderange.h> int main(void) { /* request autodetection */ int gdriver = DETECT. /* clean up */ getch(). return 0. Description getmaxmode lets you find out the maximum mode number for the currently loaded driver. if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". /* terminate with an error code */ } midx = getmaxx() / 2. which works for Borland drivers only. &gmode.%d". Return Value getmaxmode returns the maximum mode number for the current driver. getmaxmode()). ""). getch().. closegraph(). /* initialize graphics and local variables */ initgraph(&gdriver.h> #include <stdio. and convert it to a string */ sprintf(modestr. } . int midx. exit(1). outtextxy(midx. char modestr[80]. midy. modestr). /* grab the mode info. midy = getmaxy() / 2. printf("Press any key to halt:"). The minimum mode is 0. /* read result of initialization */ errorcode = graphresult().h> int getmaxmode(void).h> #include <stdlib. midy. errorcode. directly from the driver. gmode. grapherrormsg(errorcode)).Syntax #include <graphics. "This driver supports modes 0. CENTER_TEXT).h> #include <conio.

&gmode.h> int main(void) { /* request autodetection */ int gdriver = DETECT. getmaxx returns 319. /* convert max resolution values to strings */ sprintf(xrange.h> int getmaxx(void).h> #include <stdio. outtextxy(midx. char xrange[80]. midy = getmaxy() / 2.getmaxx Syntax #include <graphics. gmode. sprintf(yrange. midy. ""). int midx. midy. getmaxx()). getmaxx is invaluable for centering. getmaxy()). midy + textheight("W"). CENTER_TEXT). xrange). if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". See also getmaxy getx Example /* getmaxx example */ #include <graphics. /* initialize graphics and local variables */ initgraph(&gdriver. "X values range from 0.h> #include <stdlib. yrange)..%d". For example. printf("Press any key to halt:"). exit(1). /* terminate with an error code */ } midx = getmaxx() / 2.. errorcode. determining the boundaries of a region onscreen. outtextxy(midx.h> #include <conio. /* display the information */ settextjustify(CENTER_TEXT. and so on. Return Value getmaxx returns the maximum x screen coordinate. . getch().%d". yrange[80]. on a CGA in 320*200 mode. /* read result of initialization */ errorcode = graphresult(). "Y values range from 0. Description getmaxx returns the maximum (screen-relative) x value for the current graphics driver and mode. grapherrormsg(errorcode)).

char xrange[80]. Description getmaxy returns the maximum (screen-relative) y value for the current graphics driver and mode. int midx. midy. closegraph(). if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". For example. printf("Press any key to halt:"). grapherrormsg(errorcode)). yrange[80].h> #include <stdlib. on a CGA in 320*200 mode. } getmaxy Syntax #include <graphics. determining the boundaries of a region onscreen. /* terminate with an error code */ } midx = getmaxx() / 2. and so on. ""). See also getmaxx gety Example /* getmaxy example */ #include <graphics. &gmode. exit(1).h> #include <stdio. getmaxy returns 199. /* clean up */ getch(). /* read result of initialization */ errorcode = graphresult(). errorcode.h> int main(void) { /* request autodetection */ int gdriver = DETECT. getmaxy is invaluable for centering. /* initialize graphics and local variables */ initgraph(&gdriver. gmode.h> int getmaxy(void). return 0. Return Value getmaxy returns the maximum y screen coordinate. getch(). midy = getmaxy() / 2. /* convert max resolution values into strings */ .h> #include <conio.

xrange).h> #include <stdio. printf("Press any key to halt:"). midy+textheight("W"). "Y values range from 0. ""). The return values ("320*200 CGA P1.%d". int midx. The mode names are embedded in each driver. sprintf(yrange. errorcode. return 0.h> char *getmodename(int mode_number). /* read result of initialization */ errorcode = graphresult(). if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n".h> #include <conio. &gmode. Return Value getmodename returns a pointer to a string with the name of the graphics mode. /* display the information */ settextjustify(CENTER_TEXT. closegraph(). } getmodename Syntax #include <graphics. char numname[80]. outtextxy(midx. yrange). outtextxy(midx. midy. getmaxy())..%d". mode. "X values range from 0.. CENTER_TEXT).h> int main(void) { /* request autodetection */ int gdriver = DETECT. sprintf(xrange. modename[80]. and so on) are useful for building menus or displaying status. /* clean up */ getch(). getmaxx()). Description getmodename accepts a graphics mode number as input and returns a string containing the name of the corresponding graphics mode. See also getmaxmode getmoderange Example /* getmodename example */ #include <graphics. /* initialize graphics and local variables */ initgraph(&gdriver. midy. . gmode.h> #include <stdlib." "640*200 CGA". grapherrormsg(errorcode)).

". mode). See also getgraphmode getmaxmode getmodename initgraph setgraphmode Example /* getmoderange example */ #include <graphics. modename). The lowest permissible mode value is returned in *lomode.h> #include <stdio. If the value of graphdriver is -1. return 0. If graphdriver specifies an invalid graphics driver. numname). int *lomode. Return Value None.h> #include <conio.h> void getmoderange(int graphdriver. int *himode). outtextxy(midx. /* terminate with an error code */ } midx = getmaxx() / 2.getmodename(mode)). exit(1).h> int main(void) . both *lomode and *himode are set to -1. "%d is the current mode number. "%s is the current graphics mode. CENTER_TEXT). midy. the currently loaded driver modes are given. } getmoderange Syntax #include <graphics. and the highest permissible value is *himode. closegraph(). outtextxy(midx. midy+2*textheight("W"). graphdriver. /* get mode number and name strings */ mode = getgraphmode(). getch(). midy = getmaxy() / 2. /* clean up */ getch(). /* display the information */ settextjustify(CENTER_TEXT.h> #include <stdlib. sprintf(numname. Description getmoderange gets the range of valid graphics modes for the given graphics driver.". sprintf(modename.

midy. /* display the information */ settextjustify(CENTER_TEXT. { /* request autodetection */ int gdriver = DETECT. After calling getmouseclick. /* initialize graphics and local variables */ initgraph(&gdriver. int& x. /* clean up */ getch(). int midx. /* terminate with an error code */ } midx = getmaxx() / 2. &high). If there is no such event. gmode. CENTER_TEXT). ""). exit(1). char mrange[80]. midy = getmaxy() / 2. errorcode. outtextxy(midx. getch(). grapherrormsg(errorcode)). return 0. "This driver supports modes %d. . Description The getmouseclick function is available in the winbgim implementation of BGI graphics. /* get the mode range for this driver */ getmoderange(gdriver. /* read result of initialization */ errorcode = graphresult().. closegraph().h" voud getmouseclick(int kind. &gmode. mrange). The value of the argument kind may be any of the constants listed above. This function sets x and y to the pixel coordinates of an unprocessed event of the specified kind. then the function sets both x and y to -1. for a particular kind of event. high. &low. the ismouseclick will return false for that kind of event until another such event occurs. if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". low. int low. printf("Press any key to halt:"). int& y). /* convert mode range info. into strings */ sprintf(mrange. high). midy.%d". } getmouseclick Syntax #include "winbgim.

h" void main(void) { int maxx."). maxy. // Print a message and wait for a red pixel to be double clicked: settextstyle(DEFAULT_FONT. outtextxy(20.h file: WM_MOUSEMOVE if you want to detect a mouse movement WM_LBUTTONDBLCLK . // Coordinates of the mouse click int divisor.detect when the right mouse button is released up The middle mouse button handlers aren't working on my machine..... fillellipse(maxx/2. maxy/2.detect when the left mouse button is released up WM_MBUTTONDBLCLK .detect when the right mouse button is double clicked WM_RBUTTONDOWN . HORIZ_DIR. 2).detect when the middle mouse button is double clicked WM_MBUTTONDOWN . 50. maxy = getmaxy( ). 50). See also ismouseclick clearmouseclick Example /* mouse example */ #include "winbgim. "Left click in to end. divisor = 2. maxy/divisor)... setcolor(BLUE)... I haven't yet tracked down the reason--it could be a broken mouse or it could be a bug in my programming. // Maximum x and y pixel coordinates int x.detect when the left mouse button is double clicked WM_LBUTTONDOWN .detect when the middle mouse button is released up WM_RBUTTONDBLCLK . . 300). y.. setcolor(WHITE)... // Divisor for the length of a triangle side // Put the machine into graphics mode and get the maximum coordinates: initwindow(450.detect when the left mouse button is clicked down WM_LBUTTONUP . // Draw a white circle with red inside and a radius of 50 pixels: setfillstyle(SOLID_FILL.. The kind argument to getmouseclick is one of these constants from the winbgim. maxx = getmaxx( )...detect when the middle mouse button is clicked down WM_MBUTTONUP . while (!ismouseclick(WM_LBUTTONDOWN)) { triangle(maxx/divisor. RED)...detect when the right mouse button is clicked down WM_RBUTTONUP .. 20..

size gives the number of colors in the palette for the current graphics driver in the current mode. divisor++. Each color is either one of the 16 BGI color numbers (0 through 15) or it is -1 to indicate that the location of the palette has been set to an RGB color. x. cout << " y=" << y << endl. See also getbkcolor getcolor getdefaultpalette getmaxcolor setallpalette setpalette Example /* getpalette example */ #include <graphics. Windows Notes The winbgim version of getpalette returns a palettetype object of 16 colors. colors is an array of size bytes containing the actual raw color numbers for each entry in the palette. signed char colors[MAXCOLORS + 1]. cout << "x=" << x.h as follows: #define MAXCOLORS 15 struct palettetype { unsigned char size. // Switch back to text mode: closegraph( ). } getmouseclick(WM_LBUTTONDOWN. Return Value None. }.h> void getpalette(struct palettetype *palette). y). delay(500). } getpalette Syntax #include <graphics.h> . cout << "The mouse was clicked at: ". The MAXCOLORS constant and the palettetype structure used by getpalette are defined in graphics. getpalette cannot be used with the IBM-8514 driver. Description getpalette fills the palettetype structure pointed to by palette with information about the current palette's size and colors.

psize). char psize[80]. y. "The palette has %d modifiable entries. i. errorcode.h> #include <stdio. closegraph(). i++. pal. pal. /* convert palette info into strings */ sprintf(psize. } getpalettesize Syntax . for (i=0. i<pal. "palette[%02d]: 0x%02X". /* terminate with an error code */ } /* grab a copy of the palette */ getpalette(&pal). "Here are the current values:"). #include <stdlib. y += 2*ht. /* read result of initialization */ errorcode = graphresult(). /* initialize graphics and local variables */ initgraph(&gdriver. y. ht.h> #include <conio. pval). } } /* clean up */ getch().size != 0) { ht = textheight("W"). int y = 10. pval[20]. struct palettetype pal.colors[i]). y+=ht) { sprintf(pval. gmode. outtextxy(0. ""). getch(). if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". printf("Press any key to halt:"). if (pal.".h> int main() { /* request autodetection */ int gdriver = DETECT. y += 2*ht. return 0.size. y. &gmode. /* display the information */ outtextxy(0. grapherrormsg(errorcode)). exit(1).size). int i. outtextxy(0.

int midx. return 0. Description getpalettesize is used to determine how many palette entries can be set for the current graphics mode.h> #include <conio. For example. closegraph(). See also setallpalette setpalette Example /* getpalettesize example */ #include <graphics. &gmode. /* initialize graphics and local variables */ initgraph(&gdriver.h> int main() { /* request autodetection */ int gdriver = DETECT. grapherrormsg(errorcode)). /* terminate with an error code */ } midx = getmaxx() / 2. the programmer may also use RGB colors. midy. gmode. char psize[80]. } . if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". "The palette has %d modifiable entries. /* read result of initialization */ errorcode = graphresult(). /* clean up */ getch(). outtextxy(midx. exit(1). midy = getmaxy() / 2. /* display the information */ settextjustify(CENTER_TEXT. the EGA in color mode returns 16. errorcode. #include <graphics. midy. printf("Press any key to halt:"). psize).h> int getpalettesize(void).h> #include <stdio. getch().getpalettesize()). /* convert palette size info into string */ sprintf(psize. CENTER_TEXT). Return Value getpalettesize returns the number of palette entries in the current palette. in addition to the palette colors.".h> #include <stdlib. ""). However. Windows Notes The winbgim version of getpalettesize returns 16 for the palette color.

x. maxx. the user might set a pixel color to an RGB color. gmode. "").h> unsigned getpixel(int x. if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n".h> #define PIXEL_COUNT 1000 #define DELAY_TIME 100 /* in milliseconds */ int main(void) { /* request autodetection */ int gdriver = DETECT. maxy.h> #include <stdlib. seed. y. while (!kbhit()) { seed = random(32767). maxy = getmaxy() + 1. int y). getch(). grapherrormsg(errorcode)). the return value from getpixel might be an ordinary BGI color (integer from 0 to 15) or an RGB color. Return Value getpixel returns the color of the given pixel. /* read result of initialization */ errorcode = graphresult(). color. Therefore. See also getimage putpixel Example /* getpixel example */ #include <graphics. . maxcolor. maxcolor = getmaxcolor() + 1. /* terminate with an error code */ } maxx = getmaxx() + 1. exit(1).h> #include <stdio. int i.h> #include <conio. &gmode.y). errorcode. /* initialize graphics and local variables */ initgraph(&gdriver. Description getpixel gets the color of the pixel located at (x. Windows Notes In the winbgim version. printf("Press any key to halt:").h> #include <dos.getpixel Syntax #include <graphics. /* seed the random number generator */ srand(seed).

h> #include <stdio. int clip.h> char *clip[] = { "OFF". color). y. i<PIXEL_COUNT. srand(seed).h> #include <stdlib. y)) putpixel(x. bottom. i++) { x = random(maxx). } delay(DELAY_TIME). y = random(maxy). } } /* clean up */ getch(). for (i=0. 0). "ON" }. top.h> void getviewsettings(struct viewporttype *viewport). See also clearviewport getx gety setviewport Example /* getviewsettings example */ #include <graphics. closegraph(). i<PIXEL_COUNT. Return Value None. return 0. color = random(maxcolor). }. right. . Description getviewsettings fills the viewporttype structure pointed to by viewport with information about the current viewport. color = random(maxcolor). for (i=0. putpixel(x.h as follows: struct viewporttype { int left. i++) { x = random(maxx). The viewporttype structure used by getviewport is defined in graphics. if (color == getpixel(x. y = random(maxy). } getviewsettings Syntax #include <graphics.h> #include <conio. y.

sprintf(clipstr. getch(). exit(1). return 0. grapherrormsg(errorcode)). botstr[80]. %d) is the upper left viewport corner. /* initialize graphics and local variables */ initgraph(&gdriver. viewinfo. /* clean up */ getch().viewinfo. /* read result of initialization */ errorcode = graphresult().". closegraph(). errorcode. midy = getmaxy() / 2. midy. outtextxy(midx.bottom). midy+2*ht. clip[viewinfo. outtextxy(midx. midy. /* get information about current viewport */ getviewsettings(&viewinfo).". /* terminate with an error code */ } midx = getmaxx() / 2. CENTER_TEXT). outtextxy(midx.left. "(%d. int midx. gmode. sprintf(botstr. &gmode. ""). viewinfo. %d) is the lower right viewport corner.clip]). } getvisualpage Syntax #include "winbgim.". clipstr[80]. ht. if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". Description . clipstr). printf("Press any key to halt:"). "Clipping is turned %s.top).h" int getvisualpage(void). int main(void) { /* request autodetection */ int gdriver = DETECT.right. /* convert text information into strings */ sprintf(topstr. topstr). ht = textheight("W"). midy+4*ht. /* display the information */ settextjustify(CENTER_TEXT. char topstr[80].viewinfo. botstr). struct viewporttype viewinfo. "(%d.

/* initialize graphics and local variables */ initgraph(&gdriver. printf("Press any key to halt:"). NOTE: Using page number 0 might mess up the colors.h> #include <stdio. &gmode. I use pages 1-2 for double buffering. The getvisualpage function is available in the winbgim implementation of BGI graphics.h> int main(void) { /* request autodetection */ int gdriver = DETECT. See also getactivepage setvisualpage getx Syntax #include <graphics.h> #include <conio. See also getmaxx getviewsettings gety moveto Example /* getx example */ #include <graphics. but I have only used pages 1 and 2 myself. The original winbgi was designed to support up to 16 pages.h> #include <stdlib. /* read result of initialization */ errorcode = graphresult(). The visual graphics page might not be the one where drawing currnetly takes place. Return Value The page number of the currently visible page. ""). if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". gmode. char msg[80]. . getvisualpage gets the page number of the currently visable page (which is visible on the screen). Return Value getx returns the x-coordinate of the current position. Description getx finds the current graphics position's x-coordinate. grapherrormsg(errorcode)). The value is viewport-relative. errorcode.h> int getx(void).

%d) is the here. &gmode. The value is viewport- relative. /* clean up */ getch(). getx(). See also getmaxy getviewsettings getx moveto Example /* gety example */ #include <graphics.h> int gety(void). gmode. ""). "<-(%d. getch(). errorcode. return 0. char msg[80].h> int main(void) { /* request autodetection */ int gdriver = DETECT. getmaxy() / 2). /* terminate with an error code */ } /* move to the screen center point */ moveto(getmaxx() / 2. Return Value gety returns the y-coordinate of the current position. /* initialize graphics and local variables */ initgraph(&gdriver.".h> #include <stdio. exit(1). if (errorcode != grOk) { /* an error occurred */ .h> #include <conio. /* display the message */ outtext(msg). /* read result of initialization */ errorcode = graphresult(). Description gety returns the current graphics position's y-coordinate.h> #include <stdlib. /* create a message string */ sprintf(msg. } gety Syntax #include <graphics. gety()). closegraph().

/* terminate with an error code */ } /* move to the screen center point */ moveto(getmaxx() / 2. getch(). • sets the default text font and justification.". • sets the default fill style and pattern.h> int main(void) { /* request autodetection */ int gdriver = DETECT. printf("Press any key to halt:"). "<-(%d. /* create a message string */ sprintf(msg.h> void graphdefaults(void).h> #include <stdio. /* display the message */ outtext(msg).h> #include <stdlib.h> #include <conio. • sets the default palette colors. gety()). • moves the current position to (0. grapherrormsg(errorcode)). errorcode. closegraph(). /* clean up */ getch(). getmaxy() / 2). background color. See also initgraph setgraphmode Example /* graphdefaults example */ #include <graphics.0). printf("Graphics error: %s\n". } graphdefaults Syntax #include <graphics. and drawing color. %d) is the here. . Return Value None. Description graphdefaults resets all graphics settings to their defaults: • sets the viewport to the entire screen. exit(1). return 0. getx(). gmode.

int maxx, maxy;

/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");

/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));

printf("Press any key to halt:");
getch();
exit(1); /* terminate with an error code */
}

maxx = getmaxx();
maxy = getmaxy();

/* output line with nondefault settings */
setlinestyle(DOTTED_LINE, 0, 3);
line(0, 0, maxx, maxy);
outtextxy(maxx/2, maxy/3, "Before default values are restored.");
getch();

/* restore default values for everything */
graphdefaults();

/* clear the screen */
cleardevice();

/* output line with default settings */
line(0, 0, maxx, maxy);
outtextxy(maxx/2, maxy/3, "After restoring default values.");

/* clean up */
getch();
closegraph();
return 0;
}

grapherrormsg

Syntax
#include <graphics.h>
char * grapherrormsg(int errorcode);
Description
grapherrormsg returns a pointer to the error message string associated with errorcode,
the value returned by graphresult.
Refer to the entry for errno in the Library Reference, Chapter 4, for a list of error
messages and mnemonics.
Return Value
grapherrormsg returns a pointer to an error message string.

See also
graphresult
Example
/* grapherrormsg example */

#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

#define NONSENSE -50

int main(void)
{
/* force an error to occur */
int gdriver = NONSENSE, gmode, errorcode;

/* initialize graphics mode */
initgraph(&gdriver, &gmode, "");

/* read result of initialization */
errorcode = graphresult();

/* if an error occurred, then output descriptive error message*/
if (errorcode != grOk) {
printf("Graphics error: %s\n", grapherrormsg(errorcode));

printf("Press any key to halt:");
getch();
exit(1); /* terminate with an error code */
}

/* draw a line */
line(0, 0, getmaxx(), getmaxy());

/* clean up */
getch();
closegraph();
return 0;
}

graphresult

Syntax
#include <graphics.h>
int graphresult(void);
Description
graphresult returns the error code for the last graphics operation that reported an error
and resets the error level to grOk.
The following table lists the error codes returned by graphresult. The enumerated type
graph_errors defines the errors in this table. graph_errors is declared in graphics.h.
code constant Corresponding error message string

0 grOk No error
-1 grNoInitGraph (BGI) graphics not installed (use initgraph)
-2 grNotDetected Graphics hardware not detected
-3 grFileNotFound Device driver file not found
-4 grInvalidDriver Invalid device driver file
-5 grNoLoadMem Not enough memory to load driver
-6 grNoScanMem Out of memory in scan fill
-7 grNoFloodMem Out of memory in flood fill
-8 grFontNotFound Font file not found
-9 grNoFontMem Not enough memory to load font
-10 grInvalidMode Invalid graphics mode for selected driver
-11 grError Graphics error
-12 grIOerror Graphics I/O error
-13 grInvalidFont Invalid font file
-14 grInvalidFontNum Invalid font number
-15 grInvalidDeviceNum Invalid device number
-18 grInvalidVersion Invalid version number
Note: The variable maintained by graphresult is reset to 0 after graphresult has been
called. Therefore, you should store the value of graphresult into a temporary variable
and then test it.
Return Value
graphresult returns the current graphics error number, an integer in the range -15 to 0;
grapherrormsg returns a pointer to a string associated with the value returned by
graphresult.
See also
detectgraph
drawpoly
fillpoly
floodfill
grapherrormsg
initgraph
pieslice
registerbgidriver
registerbgifont
setallpalette
setcolor
setfillstyle
setgraphmode
setlinestyle
setpalette
settextjustify
settextstyle
setusercharsize
setviewport
setvisualpage
Example
/* graphresult example */

gmode. int right. errorcode. getmaxx().h> #include <stdlib. if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". int bottom). Description imagesize determines the size of the memory area required to store a bit image. /* clean up */ getch().h> #include <stdio.h> int main(void) { /* request autodetection */ int gdriver = DETECT. exit(1).h> #include <conio. } imagesize Syntax #include <graphics. imagesize returns 0xFFFF (-1). closegraph(). getmaxy()). If the size required for the selected image is greater than or equal to 64K . &gmode.h> unsigned imagesize(int left. return 0. grapherrormsg(errorcode)).1 bytes. ""). int top.h> #include <stdlib. /* read result of initialization */ errorcode = graphresult(). /* terminate with an error code */ } /* draw a line */ line(0.h> . Return Value imagesize returns the size of the required memory area in bytes. printf("Press any key to halt:").h> #include <stdio. getch(). 0. /* initialize graphics and local variables */ initgraph(&gdriver. #include <graphics. See also getimage putimage Example /* imagesize example */ #include <graphics.

x+(4*ARROW_SIZE). ""). /* calculate the size of the image */ size = imagesize(x. y+ARROW_SIZE). y-ARROW_SIZE. /* allocate memory to hold the image */ arrow = malloc(size). void *arrow. grapherrormsg(errorcode)). XOR_PUT). int x. /* read result of initialization */ errorcode = graphresult(). if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". maxx.#include <conio. gmode. y-ARROW_SIZE. x+(4*ARROW_SIZE). x += ARROW_SIZE. } . /* initialize graphics and local variables */ initgraph(&gdriver. &gmode. XOR_PUT). arrow. int y). arrow).h> #define ARROW_SIZE 10 void draw_arrow(int x. y. /* plot new image */ putimage(x. int main(void) { /* request autodetection */ int gdriver = DETECT. return 0. y-ARROW_SIZE. if (x >= maxx) x = 0. getch(). y+ARROW_SIZE. closegraph(). y-ARROW_SIZE. /* terminate with an error code */ } maxx = getmaxx(). } /* clean up */ free(arrow). y = getmaxy() / 2. /* repeat until a key is pressed */ while (!kbhit()) { /* erase old image */ putimage(x. x = 0. errorcode. unsigned int size. arrow. exit(1). /* grab the image */ getimage(x. /* draw the image to be grabbed */ draw_arrow(x. y). printf("Press any key to halt:").

BGI) must be in the current directory. the driver files (*. 2*ARROW_SIZE).CHR). linerel(2*ARROW_SIZE. char *pathtodriver). Description initgraph initializes the graphics system by loading a graphics driver from disk (or validating a registered driver). if pathtodriver is null. you can link a graphics driver file (or several of them) directly into your executable program file. which is defined in graphics. int *graphmode. linerel(-2*ARROW_SIZE. then loading the appropriate . To start the graphics system. *graphdriver is an integer that specifies the graphics driver to be used. color. and so on) and resets graphresult to 0. first call the initgraph function. You can tell initgraph to use a particular graphics driver and mode.BGI file from disk. int y) { /* draw an arrow on the screen */ moveto(x. graphics_drivers constant Numeric value DETECT 0 (requests autodetect) CGA 1 MCGA 2 EGA 3 EGA64 4 EGAMONO 5 IBM8514 6 . linerel(4*ARROW_SIZE. This is also the path settextstyle searches for the stroked character font files (*. linerel(0. Accordingly.h> void initgraph(int *graphdriver. viewport. initgraph loads a graphics driver by allocating memory for the driver (through _graphgetmem). and putting the system into graphics mode. initgraph loads the graphics driver and puts the system into graphics mode. pathtodriver specifies the directory path where initgraph looks for graphics drivers. 0). As an alternative to this dynamic loading scheme. initgraph first looks in the path specified in pathtodriver. Normally. You can give it a value using a constant of the graphics_drivers enumeration type. initgraph also resets all graphics settings to their defaults (current position. then (if they are not there) in the current directory. -1*ARROW_SIZE). void draw_arrow(int x. -1*ARROW_SIZE). } initgraph Syntax #include <graphics. or to autodetect the attached video adapter at run time and pick the corresponding driver. palette.h and listed below. y). If you tell initgraph to autodetect. it calls detectgraph to select a graphics driver and mode.

You can select the background color (entry #0) in each of these palettes. in which case. *graphmode is set by initgraph to the highest resolution available for the detected driver). Columns Graphics Driver graphics_mode Value x Rows Palette Pages CGA CGAC0 0 320 x 200 C0 1 CGAC1 1 320 x 200 C1 1 CGAC2 2 320 x 200 C2 1 CGAC3 3 320 x 200 C3 1 CGAHI 4 640 x 200 2 color 1 MCGA MCGAC0 0 320 x 200 C0 1 MCGAC1 1 320 x 200 C1 1 MCGAC2 2 320 x 200 C2 1 MCGAC3 3 320 x 200 C3 1 MCGAMED 4 640 x 200 2 color 1 MCGAHI 5 640 x 480 2 color 1 EGA EGALO 0 640 x 200 16 color 4 EGAHI 1 640 x 350 16 color 2 EGA64 EGA64LO 0 640 x 200 16 color 1 . and C3 refer to the four predefined four-color palettes available on CGA (and compatible) systems. The exception is graphdriver = DETECT. C1. graphdriver and graphmode must be set to valid values from the following tables. C2. which is defined in graphics.h and listed below.HERCMONO 7 ATT400 8 VGA 9 PC3270 10 *graphmode is an integer that specifies the initial graphics mode (unless *graphdriver equals DETECT. Palette listings C0. or you will get unpredictable results. but the other colors are fixed. Palette Number Three Colors 0 LIGHTGREEN LIGHTRED YELLOW 1 LIGHTCYAN LIGHTMAGENTA WHITE 2 GREEN RED BROWN 3 CYAN MAGENTA LIGHTGRAY After a call to initgraph. *graphdriver is set to the current graphics driver. and *graphmode is set to the current graphics mode. You can give *graphmode a value using a constant of the graphics_modes enumeration type.

If an error occurred. As an alternative. See also closegraph detectgraph getdefaultpalette getdrivername getgraphmode getmoderange . *graphdriver is set to -2. EGA64HI 1 640 x 350 4 color 1 EGA-MONO EGAMONOHI 3 640 x 350 2 color 1 w/64K EGAMONOHI 3 640 x 350 2 color 2 w/256K HERC HERCMONOHI 0 720 x 348 2 color 2 ATT400 ATT400C0 0 320 x 200 C0 1 ATT400C1 1 320 x 200 C1 1 ATT400C2 2 320 x 200 C2 1 ATT400C3 3 320 x 200 C3 1 ATT400MED 4 640 x 200 2 color 1 ATT400HI 5 640 x 400 2 color 1 VGA VGALO 0 640 x 200 16 color 2 VGAMED 1 640 x 350 16 color 2 VGAHI 2 640 x 480 16 color 1 PC3270 PC3270HI 0 720 x 350 2 color 1 IBM8514 IBM8514HI 0 640 x 480 256 color ? IBM8514LO 0 1024 x 768 256 color ? Return Value initgraph always sets the internal error code. -4. -3. CGAC3) will create a 320 x 200 window. height) instead of initgraph. For example. the user may call initwindow(width. on success. it sets the code to 0. and graphresult returns the same value as listed below: Constant Name Number Meaning grNotDetected -2 Cannot detect a graphics card grFileNotFound -3 Cannot find driver file grInvalidDriver -4 Invalid driver grNoLoadMem -5 Insufficient memory to load driver Windows Notes The winbgim version of initgraph uses its parameters only to determine the size of the window that will be created. initgraph(CGA. or -5.

graphdefaults graphresult installuserdriver registerbgidriver registerbgifont restorecrtmode setgraphbufsize setgraphmode Example /* initgraph example */ #include <graphics. exit(1).h> #include <stdio. grapherrormsg(errorcode)). gmode. /* clean up */ getch(). closegraph(). getch(). printf("Press any key to halt:"). "").h> #include <conio. 0.h> int main(void) { /* request autodetection */ int gdriver = DETECT. return 0. errorcode. } initwindow Syntax #include "winbgim. &gmode. getmaxx(). /* return with error code */ } /* draw a line */ line(0.h> #include <stdlib. /* read result of initialization */ errorcode = graphresult(). getmaxy()).h" void initwindow(int width. /* initialize graphics mode */ initgraph(&gdriver. if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n". Description . int height).

The name parameter is the name of the new device-driver file (. and the detect parameter is a pointer to an optional autodetect function that can accompany the new driver. There are two ways to use this vendor-supplied driver. getmaxx(). When you install the driver (by calling installuserdriver).h> int installuserdriver(char *name. Before initgraph calls its built-in autodetection function (detectgraph). } installuserdriver Syntax #include <graphics.h. Description installuserdriver lets you add a vendor-added device driver to the BGI internal table. along with the device driver's file name. you pass the address of this function. /* draw a line */ line(0. The other. call initgraph and let it go through its normal autodetection process.h" int main(void) { /* initialize graphics window at 400 x 300 */ initwindow(400. closegraph(). it first calls the SGA autodetect . 0. 300).BGI). return 0.BGI). This autodetect function takes no parameters and returns an integer value.h. getmaxy()). more general way to use this driver is to link in an autodetect function that will be called by initgraph as part of its hardware-detection logic (presumably. Suppose you have a new video card called the Spiffy Graphics Array (SGA) and that the SGA manufacturer provided you with a BGI device driver (SGA. You do not need to include conio. The initwindow function is available in the winbgim implementation of BGI graphics. See also closegraph initgraph Example /* initwindow example */ #include "winbgim. /* clean up */ getch(). the manufacturer of the SGA gave you this autodetect function). The function initializes the graphics system by opening a graphics window of the specified size. just include winbgim. After you install the device-driver file name and the SGA autodetect function. int huge (*detect)(void)). The easiest way to use this driver is to install it by calling installuserdriver and then passing the return value (the assigned driver number) directly to initgraph. Return Value None.

If the SGA autodetect function doesn't find the SGA hardware. int main(void) { int gdriver. gmode. detectEGA). /* draw a line */ line(0. &gmode. closegraph(). /* must force use of detection routine */ gdriver = DETECT. If. it returns a nonnegative mode number. however. void checkerrors(void). /* check for any initialization errors */ checkerrors(). getmaxy()). function. 0. /* initialize graphics and local variables */ initgraph(&gdriver. the autodetect function determines that an SGA is present. You can install up to ten drivers at one time.BGI. puts the hardware into the default graphics mode recommended by the autodetect function. ""). Return Value The value returned by installuserdriver is the driver number parameter you would pass to initgraph in order to select the newly installed driver manually. /* check for any installation errors */ checkerrors(). /* clean up */ getch(). then initgraph locates and loads SGA. getmaxx(). and initgraph proceeds with its normal hardware detection logic (which can include calling any other vendor-supplied autodetection functions in the order in which they were "installed"). it returns a value of -11 (grError). Windows Notes installuserdriver is not available in the winbgim implementation. and finally returns control to your program. } /* detects EGA or VGA cards */ int huge detectEGA(void) . return 0. /* install a user written device driver */ gdriver = installuserdriver("EGA". See also initgraph registerbgidriver Example /* installuserdriver example */ #include #include #include #include /* function prototypes */ int huge detectEGA(void).

a value of -11 (grError) is returned. See also settextstyle Example /* installuserfont example */ #include <graphics. if (errorcode != grOk) { printf("Graphics error: %s\n".h> #include <stdlib.h> int installuserfont(char *name). Windows Notes installuserfont is not available in the winbgim implementation. &mode). mode. /* return suggested video mode number */ else return grError. if ((driver == EGA) || (driver == VGA)) return sugmode. exit(1). { int driver. . detectgraph(&driver. } } installuserfont Syntax #include <graphics. grapherrormsg(errorcode)). If the internal font table is full. Description name is a file name in the current directory (pathname is not supported) of a font file containing a stroked font.h> /* function prototype */ void checkerrors(void). printf("Press any key to halt:"). getch(). /* read result of last graphics operation */ errorcode = graphresult(). Up to twenty fonts can be installed at one time. /* return an error code */ } /* check for and report any graphics errors */ void checkerrors(void) { int errorcode. sugmode = 0.h> #include <conio. Return Value installuserfont returns a font ID number that can then be passed to settextstyle to select the corresponding font.h> #include <stdio.

midy = getmaxy() / 2. /* check for any installation errors */ checkerrors(). /* check for any initialization errors */ checkerrors(). printf("Press any key to halt:"). int userfont. midy. getch().h" . return 0. /* install a user-defined font file */ userfont = installuserfont("USER. HORIZ_DIR. int midx. &gmode. closegraph(). /* select the user font */ settextstyle(userfont. midx = getmaxx() / 2.CHR"). midy. /* read result of last graphics operation */ errorcode = graphresult(). /* clean up */ getch(). /* output some text */ outtextxy(midx. "Testing!"). /* initialize graphics and local variables */ initgraph(&gdriver. 4). ""). if (errorcode != grOk) { printf("Graphics error: %s\n". } } ismouseclick Syntax #include "winbgim. gmode. } /* check for and report any graphics errors */ void checkerrors(void) { int errorcode. grapherrormsg(errorcode)). int main(void) { /* request autodetection */ int gdriver = DETECT. exit(1).

detect when the right mouse button is released up The middle mouse button handlers aren't working on my machine. A mouse event can be processed by calling getmouseclick (which gets the coordinates of the event). I haven't yet tracked down the reason--it could be a broken mouse or it could be a bug in my programming..detect when the right mouse button is double clicked WM_RBUTTONDOWN .h" void main(void) { int maxx. . // Draw a white circle with red inside and a radius of 50 pixels: setfillstyle(SOLID_FILL. // Divisor for the length of a triangle side // Put the machine into graphics mode and get the maximum coordinates: initwindow(450. This function returns true if there is an unprocessed mouse event of the specified kind...detect when the left mouse button is released up WM_MBUTTONDBLCLK .. // Maximum x and y pixel coordinates int x. Description The ismouseclick function is available in the winbgim implementation of BGI graphics..detect when the middle mouse button is released up WM_RBUTTONDBLCLK .detect when the middle mouse button is clicked down WM_MBUTTONUP . y. maxx = getmaxx( ).h file: WM_MOUSEMOVE if you want to detect a mouse movement WM_LBUTTONDBLCLK . otherwise false. or by calling clearmouseclick (which processes the event without providing its coordinates). RED).. maxy = getmaxy( )..detect when the middle mouse button is double clicked WM_MBUTTONDOWN .... See also getmouseclick clearmouseclick Example /* mouse example */ #include "winbgim. // Coordinates of the mouse click int divisor.. bool ismouseclick(int kind)...detect when the left mouse button is double clicked WM_LBUTTONDOWN . Return Value True if there is an unprocessed mouse event of the specified kind. The argument to ismouseclick is one of these constants from the winbgim...detect when the right mouse button is clicked down WM_RBUTTONUP . maxy. 300)...detect when the left mouse button is clicked down WM_LBUTTONUP ..

otherwise false. "Left click in to end. setcolor(WHITE). See also kbhit Example #include "winbgim. the Windows focus must be in the graphics window). y).h" int kbhit(void). Description The kbhit function is available in the winbgim implementation of BGI graphics. outtextxy(20. int main( ) { int i. The function returns true (non- zero) if there is a character in the input buffer ready to read. HORIZ_DIR. // Print a message and wait for a red pixel to be double clicked: settextstyle(DEFAULT_FONT. 300). cout << "The mouse was clicked at: ". divisor = 2.h" #include <stdio. // Initialize the graphics window. Otherwise it returns false. while (!ismouseclick(WM_LBUTTONDOWN)) { triangle(maxx/divisor. } getmouseclick(WM_LBUTTONDOWN. int value). maxy/divisor).h. divisor++. // Switch back to text mode: closegraph( ).e. cout << " y=" << y << endl. 20. 50). just include winbgim. maxy/2. cout << "x=" << x. fillellipse(maxx/2. x. init_window(400. 50.. the user must click in the graphics window (i. int y.h> // Provides sprintf void outintxy(int x. delay(500). setcolor(BLUE). // Convert some numbers to strings and draw them in graphics window: . In order to work. You do not need to include conio.h."). Return Value True (non-zero) if there is a character in the input buffer. 2). } kbhit Syntax #include "winbgim.

h> int main(void) { /* request autodetection */ int gdriver = DETECT. i++) { outintxy(20 + (i/10)*40 . for (i = 0. !kbhit( ). without updating the current position (CP). 130. outtextxy(10. int y2). "Click in this graphics window."). Return Value None. . errorcode. See also getlinesettings linerel lineto setcolor setlinestyle setwritemode Example /* line example */ #include <graphics. "and then press a key to stop. gmode. Description line draws a line in the current color. i). (x1. "Here are some numbers:"). ""). outtextxy(20. &gmode. int x2. digit_string). 140.h> #include <stdio.h> #include <stdlib. (i % 10)*+10. using the current line style and thickness between the two points specified.y1) and (x2. int xmax. delay(4000). /* initialize graphics and local variables */ initgraph(&gdriver. y.h> #include <conio."). 10. "%d".h> void line(int x1. value). outtextxy(20. outtextxy(x. ymax. int y1. int y. } line Syntax #include <graphics. } void outintxy(int x.y2). } closegraph( ). sprintf(digit_string. int value) { char digit_string[20].

/* draw a diagonal line */ line(0. } setcolor(getmaxcolor()). gmode. xmax = getmaxx().h> #include <stdio.h> #include <stdlib.h> int main(void) { /* request autodetection */ int gdriver = DETECT.dy) from the CP.h> #include <conio. return 0. . exit(1). ymax). } linerel Syntax #include <graphics.h> void linerel(int dx. printf("Press any key to halt:"). See also getlinesettings line lineto setcolor setlinestyle setwritemode Example /* linerel example */ #include <graphics. xmax. grapherrormsg(errorcode)). getch(). /* clean up */ getch().dy). 0. ymax = getmaxy(). /* read result of initialization */ errorcode = graphresult(). char msg[80]. Return Value None. closegraph(). Description linerel draws a line from the CP (current position) to a point that is a relative distance (dx. int dy). errorcode. if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". The CP is advanced by (dx.

then moves the CP to (x. Return Value None. if (errorcode != grOk) { printf("Graphics error: %s\n".y). getx(). exit(1). gety()). gety()).30) */ sprintf(msg.h> . /* draw line to a point a relative distance away from current CP */ linerel(100. int y).y). outtext(msg). %d)". /* clean up */ getch(). outtextxy(20.30). ""). " (%d. msg). } lineto Syntax #include <graphics. " (%d. } /* move the CP to location (20.30.h> void lineto(int x.30) */ moveto(20. 100). /* read result of initialization */ errorcode = graphresult(). /* initialize graphics and local variables */ initgraph(&gdriver. getx(). /* create and output a message at CP */ sprintf(msg. return 0. getch(). &gmode. closegraph(). %d)". Description lineto draws a line from the CP (current position) to (x. /* create and output a message at (20. See also getlinesettings line linerel setcolor setlinestyle setwritemode Example /* lineto example */ #include <graphics. grapherrormsg(errorcode)). printf("Press any key to halt:").

errorcode. " (%d. %d)".30) */ moveto(20.h> int main(void) { /* request autodetection */ int gdriver = DETECT. outtext(msg). 30). Return Value Most recent x coordinate of the mouse within the graphics window See also .h> #include <stdio. } /* move the CP to location (20. return 0.30. /* read result of initialization */ errorcode = graphresult(). getx(). " (%d. #include <stdlib. /* create and output a message at CP */ sprintf(msg. getx(). if (errorcode != grOk) { printf("Graphics error: %s\n". /* create and output a message at (20.h" int mousex(void). /* initialize graphics and local variables */ initgraph(&gdriver. X- coordinates start with 0 at the left edge of the window and increase to getmaxx( ) at the right edge of the window. closegraph(). } mousex Syntax #include "winbgim.100) */ lineto(100. gety()).30) */ sprintf(msg.h> #include <conio. gety()). msg). grapherrormsg(errorcode)). exit(1). getch(). &gmode. %d)". gmode. It returns the most recent x coordinate of the mouse within the graphics window. Description The mousex function is available in the winbgim implementation of BGI graphics. /* draw a line to (100. char msg[80]. 100). outtextxy(20. /* clean up */ getch(). ""). printf("Press any key to halt:").

h" // The click_handler will be called whenever the left mouse button is // clicked. 2). RED). 50.base/2. Note that in general // all handlers should be quick. // Maximum x and y pixel coordinates int divisor. // Register the function that handles a left mouse click registermousehandler(WM_LBUTTONDOWN. line(maxx/2 . line(maxx/2 + base/2. } void main(void) { int maxx. maxy/2.10. maxy = getmaxy( ).base/2.10. maxy .10). maxy . 50). bool red_clicked = false. maxx = getmaxx( ). void triangle(int base.10 .10. maxx/2 + base/2. maxy . click_handler). 300). // Draw a white circle with red inside and a radius of 50 pixels: setfillstyle(SOLID_FILL. line(maxx/2 . } // Call this function to draw an isosoles triangle with the given base and // height. red_clicked = false. int y) { if (getpixel(x. maxx/2.height). maxx/2. The triangle will be drawn just above the botton of the screen. getmaxx mousey registermousehandler Example /* mouse example */ #include "winbgim. fillellipse(maxx/2.10 . int height) { int maxx = getmaxx( ). maxy . maxy . void click_handler(int x.y) == RED) red_clicked = true. If they need to do more than a little // work. maxy. outtextxy(20. then the boolean // variable red_clicked is set to true. . HORIZ_DIR. "Left click in RED to end. maxy .height). // and then return."). // Print a message and wait for a red pixel to be double clicked: settextstyle(DEFAULT_FONT. If so. 20. setcolor(WHITE). It checks copies the x. int maxy = getmaxy( ).y coordinates of the click to // see if the click was on a red pixel. setcolor(BLUE). // Divisor for the length of a triangle side // Put the machine into graphics mode and get the maximum coordinates: initwindow(450. they should set a variable that will trigger the work going.

cout << " y=" << mousey( ) << endl.h" // The click_handler will be called whenever the left mouse button is // clicked.h" int mousey(void). int y) { if (getpixel(x. // and then return.y) == RED) red_clicked = true.y coordinates of the click to // see if the click was on a red pixel. void click_handler(int x. maxy/divisor). } mousey Syntax #include "winbgim. If they need to do more than a little // work. } cout << "The mouse was clicked at: ". It returns the most recent y coordinate of the mouse within the graphics window. while (!red_clicked) { triangle(maxx/divisor. Description The mousey function is available in the winbgim implementation of BGI graphics. they should set a variable that will trigger the work going. cout << "x=" << mousex( ). Return Value Most recent y coordinate of the mouse within the graphics window See also getmaxy mousey registermousehandler Example /* mouse example */ #include "winbgim. It checks copies the x. // Switch back to text mode: closegraph( ). Note that in general // all handlers should be quick. delay(500). bool red_clicked = false. divisor++. } // Call this function to draw an isosoles triangle with the given base and . then the boolean // variable red_clicked is set to true. If so. Y- coordinates start with 0 at the top edge of the window and increase to getmaxy( ) at the bottom edge of the window. divisor = 2.

maxy . int maxy = getmaxy( ). 50). line(maxx/2 . 50. fillellipse(maxx/2. maxy . maxy/divisor). 2). // Draw a white circle with red inside and a radius of 50 pixels: setfillstyle(SOLID_FILL. maxx/2. The triangle will be drawn just above the botton of the screen. line(maxx/2 + base/2.base/2.base/2. // height. maxy .10. maxy/2. // Register the function that handles a left mouse click registermousehandler(WM_LBUTTONDOWN.10 . cout << " y=" << mousey( ) << endl. // Print a message and wait for a red pixel to be double clicked: settextstyle(DEFAULT_FONT. maxy .10 . void triangle(int base. maxx = getmaxx( ). HORIZ_DIR. RED). int dy).10). outtextxy(20. "Left click in RED to end. } moverel Syntax #include <graphics. } void main(void) { int maxx. red_clicked = false. maxy = getmaxy( ). maxy . setcolor(BLUE). 300). // Maximum x and y pixel coordinates int divisor. // Divisor for the length of a triangle side // Put the machine into graphics mode and get the maximum coordinates: initwindow(450.height).height). divisor = 2. maxx/2 + base/2. divisor++. click_handler). line(maxx/2 .10."). maxy. int height) { int maxx = getmaxx( ).10. delay(500). maxy . // Switch back to text mode: closegraph( ). maxx/2. cout << "x=" << mousex( ).h> void moverel(int dx. } cout << "The mouse was clicked at: ". . 20. setcolor(WHITE). while (!red_clicked) { triangle(maxx/divisor.

30) */ sprintf(msg.h> int main(void) { /* request autodetection */ int gdriver = DETECT. gety(). closegraph().Description moverel moves the current position (CP) dx pixels in the x direction and dy pixels in the y direction. gety().30. See also moveto Example /* moverel example */ #include <graphics. /* terminate with an error code */ } /* move the CP to location (20. msg). /* initialize graphics and local variables */ initgraph(&gdriver. getmaxcolor()). if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". gety()). /* create and output a message at CP */ sprintf(msg.30). ""). /* plot a pixel at the CP */ putpixel(getx(). grapherrormsg(errorcode)). outtext(msg).h> #include <stdio. printf("Press any key to halt:"). getmaxcolor()). exit(1). gmode. /* move to a point a relative distance away from the current CP */ moverel(100.h> #include <conio. /* create and output a message at (20. gety()). outtextxy(20. " (%d. " (%d. Return Value None. 100). /* read result of initialization */ errorcode = graphresult(). /* plot a pixel at the CP */ putpixel(getx(). &gmode. %d)".30) */ moveto(20. getx(). return 0. /* clean up */ getch(). char msg[80]. %d)". getx(). getch(). errorcode.h> #include <stdlib. } .

/* terminate with an error code */ } /* move the CP to location (20. ""). &gmode. gety()). msg).h> #include <stdio.h> #include <conio. %d)". if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". Return Value None.30) */ moveto(20. getx().30) */ sprintf(msg. getx().h> #include <stdlib. gety(). /* read result of initialization */ errorcode = graphresult(). " (%d. gety()). /* plot a pixel at the CP */ putpixel(getx().30. grapherrormsg(errorcode)).h> void moveto(int x. Description moveto moves the current position (CP) to viewport position (x. getmaxcolor()). /* create and output a message at (20. printf("Press any key to halt:"). %d)".y).h> int main(void) { /* request autodetection */ int gdriver = DETECT. int y). exit(1).30). outtextxy(20. getmaxcolor()). getch(). gety(). /* plot a pixel at the CP */ putpixel(getx(). /* initialize graphics and local variables */ initgraph(&gdriver. errorcode. /* create and output a message at CP */ sprintf(msg. char msg[80]. See also moverel Example /* moveto example */ #include <graphics.moveto Syntax #include <graphics.100) */ moveto(100. " (%d. /* move to (100. . gmode.100).

gmode. direction. and size.h> int main(void) { /* request autodetection */ int gdriver = DETECT. outtext outputs textstring at the current position (CP). closegraph(). If a string is printed with the default font using outtext. If the horizontal text justification is LEFT_TEXT and the text direction is HORIZ_DIR. return 0. } outtext Syntax #include <graphics. Description outtext displays a text string in the viewport. any part of the string that extends outside the current viewport is truncated.h> void outtext(char *textstring). .h> #include <conio. the CP remains unchanged. /* initialize graphics and local variables */ initgraph(&gdriver. grapherrormsg(errorcode)). To maintain code compatibility when using several fonts. use textwidth and textheight to determine the dimensions of the string.h> #include <stdio. Otherwise. it will not work in text mode. using the current font. midy. outtext(msg). See also gettextsettings outtextxy settextjustify textheight textwidth Example /* outtext example */ #include <graphics. Return Value None. ""). outtext is for use in graphics mode. &gmode. if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". the CP's x- coordinate is advanced by textwidth(textstring).h> #include <stdlib. /* read result of initialization */ errorcode = graphresult(). /* clean up */ getch(). errorcode. int midx.

direction. char *textstring). use textwidth and textheight to determine the dimensions of the string. return 0. See also gettextsettings outtext settextjustify textheight textwidth Example /* outtextxy example */ #include <graphics.h> #include <stdio. Return Value None. getch(). any part of the string that extends outside the current viewport is truncated. outtext("a "). outtextxy is for use in graphics mode. midy = getmaxy() / 2. y). it will not work in text mode. } outtextxy Syntax #include <graphics. outtext("test. int y. To maintain code compatibility when using several fonts. If a string is printed with the default font using outtext or outtextxy. /* output text starting at the CP */ outtext("This ")."). and size. /* clean up */ getch().h> void outtextxy(int x.h> #include <conio.h> int main(void) . /* terminate with an error code */ } midx = getmaxx() / 2. midy).h> #include <stdlib. exit(1). /* move the CP to the center of the screen */ moveto(midx. Description outtextxy displays a text string in the viewport at the given position (x. using the current justification settings and the current font. closegraph(). printf("Press any key to halt:"). outtext("is ").

with 0 degrees at 3 o'clock. midy. errorcode. } pieslice Syntax #include <graphics. If you're using a CGA or monochrome adapter. int midx. ""). /* clean up */ getch(). /* read result of initialization */ errorcode = graphresult(). /* output text at center of the screen.y) with a radius given by radius. "This is a test. CP doesn't get changed */ outtextxy(midx. The slice is outlined in the current drawing color and then filled using the current fill pattern and fill color. printf("Press any key to halt:"). closegraph(). midy. The angles for pieslice are given in degrees. /* terminate with an error code */ } midx = getmaxx() / 2. The slice travels from stangle to endangle. return 0. if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n"."). int radius). the examples in online Help that show how to use graphics functions might not produce the expected results. getch(). See also fillelipse graphresult sector .h> void pieslice(int x. midy = getmaxy() / 2. Description pieslice draws and fills a pie slice centered at (x. Return Value None. and so on. gmode. use the value 1 (one) instead of the symbolic color constant. int stangle. int endangle. They are measured counterclockwise. { /* request autodetection */ int gdriver = DETECT. &gmode. 90 degrees at 12 o'clock. If your system runs on a CGA or monochrome adapter. /* initialize graphics and local variables */ initgraph(&gdriver. exit(1). int y. and see the second example under arc whis shows how to use the pieslice function. grapherrormsg(errorcode)).

pieslice(midx. grapherrormsg(errorcode)). closegraph(). getch(). midy = getmaxy() / 2.h> #include <conio. int midx. midy.h> #include <stdlib. if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n". The op parameter to putimage specifies a combination operator that controls how the color for each destination pixel onscreen is computed. stangle. int op). int top.top). /* read result of initialization */ errorcode = graphresult(). based on the pixel already . /* terminate with an error code */ } midx = getmaxx() / 2. radius). errorcode.h> int main(void) { /* request autodetection */ int gdriver = DETECT. int stangle = 45. radius = 100. endangle. with the upper left corner of the image placed at (left. midy. setfillstyle Example /* pieslice example */ #include <graphics. gmode. } putimage Syntax #include <graphics. ""). getmaxcolor()). return 0. Description putimage puts the bit image previously saved with getimage back onto the screen. printf("Press any key to halt:"). /* initialize graphics and local variables */ initgraph(&gdriver. &gmode. void *bitmap.h> #include <stdio. /* set fill style and draw a pie slice */ setfillstyle(EMPTY_FILL. /* clean up */ getch().h> void putimage(int left. endangle = 135. exit(1). bitmap points to the area in memory where the source image is stored.

x = 0. Return Value None. printf("Press any key to halt:"). y = getmaxy() / 2. The enumeration putimage_ops. int x. XOR_PUT XORs the source image with the image already onscreen. y. "").h> #include <stdlib. onscreen and the corresponding source pixel in memory. int main() { /* request autodetection */ int gdriver = DETECT. errorcode. void *arrow. y). &gmode.h. if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n". . and so on. OR_PUT ORs the source image with that onscreen. exit(1).h> #include <conio. COPY_PUT copies the source bitmap image onto the screen. /* terminate with an error code */ } maxx = getmaxx(). maxx. as defined in graphics. errorcode = graphresult(). /* initialize graphics and local variables */ initgraph(&gdriver.h> #define ARROW_SIZE 10 void draw_arrow(int x. int y). getch(). See also getimage imagesize putpixel setvisualpage Example /* putimage example */ #include <graphics. draw_arrow(x. gmode. Name Value Description COPY_PUT 0 Copy XOR_PUT 1 Exclusive or OR_PUT 2 Inclusive or AND_PUT 3 And NOT_PUT 4 Copy the inverse of the source In other words. gives names to these operators.h> #include <stdio. unsigned int size. grapherrormsg(errorcode)).

h> #include <stdlib. linerel(2*ARROW_SIZE. XOR_PUT). x+(4*ARROW_SIZE). linerel(4*ARROW_SIZE. int y) { moveto(x. Windows Notes The winbgim version allows the color argument to be an ordinary BGI color (from 0 to 15) or an RGB color. arrow. /* grab the image */ getimage(x. y+ARROW_SIZE. Return Value None. y). Description putpixel plots a point in the color defined by color at (x. int y. linerel(0. -1*ARROW_SIZE). XOR_PUT). return 0. y-ARROW_SIZE. x += ARROW_SIZE.h> void putpixel(int x. y+ARROW_SIZE). arrow = malloc(size). 0). x+(4*ARROW_SIZE). -1*ARROW_SIZE). linerel(-2*ARROW_SIZE. y-ARROW_SIZE. if (x >= maxx) x = 0. y-ARROW_SIZE. int color). /* plot new image */ putimage(x. 2*ARROW_SIZE). arrow. See also getpixel putimage Example /* putpixel example */ #include <graphics. } void draw_arrow(int x. } putpixel Syntax #include <graphics. /* repeat until a key is pressed */ while (!kbhit()) { /* erase old image */ putimage(x.h> . y-ARROW_SIZE. /* calculate the size of the image and allocate space for it */ size = imagesize(x. arrow). closegraph(). } free(arrow).y).

i<PIXEL_COUNT. color). getch(). i<PIXEL_COUNT. while (!kbhit()) { /* seed the random number generator */ seed = random(32767). if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". } delay(DELAY_TIME). grapherrormsg(errorcode)). gmode. return 0.#include <stdio.h> #define PIXEL_COUNT 1000 #define DELAY_TIME 100 /* in milliseconds */ int main() { /* request autodetection */ int gdriver = DETECT. closegraph(). maxcolor = getmaxcolor() + 1. putpixel(x. maxcolor. y = random(maxy).h> #include <dos. if (color == getpixel(x. color = random(maxcolor). } } /* clean up */ getch(). /* initialize graphics and local variables */ initgraph(&gdriver. color. x. int i. ""). y.h> #include <conio. y)) putpixel(x. /* terminate with an error code */ } maxx = getmaxx() + 1. y. maxy = getmaxy() + 1. maxx. } . /* read result of initialization */ errorcode = graphresult(). maxy. i++) { x = random(maxx). i++) { x = random(maxx). for (i=0. color = random(maxcolor). exit(1). y = random(maxy). printf("Press any key to halt:"). errorcode. y. &gmode. 0). srand(seed). srand(seed). seed. for (i=0.

return 0. and drawing color.h> #include <stdio. bottom = getmaxy() / 2 + 50.50. errorcode. (left. right. /* draw a rectangle */ rectangle(left. thickness. right = getmaxx() / 2 + 50. } .h> void rectangle(int left. getch(). /* terminate with an error code */ } left = getmaxx() / 2 . Description rectangle draws a rectangle in the current line style.h> #include <stdlib.50. "").top) is the upper left corner of the rectangle.bottom). /* clean up */ getch(). gmode.right. exit(1). int top. top = getmaxy() / 2 . printf("Press any key to halt:"). int right. grapherrormsg(errorcode)).h> int main(void) { /* request autodetection */ int gdriver = DETECT.top. Return Value None.bottom) is its lower right corner. closegraph(). if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". int left.h> #include <conio. and (right. &gmode.rectangle Syntax #include <graphics. /* initialize graphics and local variables */ initgraph(&gdriver. bottom. See also bar bar3d setcolor setlinestyle Example /* rectangle example */ #include <graphics. /* read result of initialization */ errorcode = graphresult(). int bottom). top.

h> #include <conio. you must pass the result of registerbgidriver to initgraph as the driver number to be used. Otherwise. /* report any registration errors */ if (errorcode < 0) { printf("Graphics error: %s\n".h> int registerbgidriver(void (*driver)(void)).OBJ file (using BGIOBJ. if the code is valid. it registers the code in internal tables. exit(1). grapherrormsg(errorcode)). errorcode. This routine checks the linked-in code for the specified driver.LIB */ errorcode = registerbgidriver(EGAVGA_driver). Description registerbgidriver enables a user to load a driver file and "register" the driver. See also graphresult initgraph installuserdriver registerbgifont Example /* registerbgidriver example */ #include <graphics. you also tell the compiler (and linker) to link in the object file with that public name. /* terminate with an error code */ } /* initialize graphics and local variables */ initgraph(&gdriver. gmode. &gmode.EXE.h> #include <stdlib. registerbgidriver returns the driver number. .h> #include <stdio. Windows Notes registerbgidriver is not available in the winbgim implementation. initgraph uses the registered driver. A user-registered driver can be loaded from disk onto the heap.h> int main(void) { /* request autodetection */ int gdriver = DETECT. /* register a driver that was added into GRAPHICS. or converted to an . By using the name of a linked-in driver in a call to registerbgidriver. printf("Press any key to halt:"). Once its memory location has been passed to registerbgidriver. Calling registerbgidriver informs the graphics system that the driver pointed to by driver was included at link time.EXE) and linked into the . Return Value registerbgidriver returns a negative graphics error code if the specified driver or font is invalid. If you register a user-supplied driver. ""). getch().registerbgidriver Syntax #include <graphics.

/* read result of initialization */ errorcode = graphresult(). Windows Notes registerbgifont is not available in the winbgim implementation. you also tell the compiler (and linker) to link in the object file with that public name. Return Value registerbgifont returns a negative graphics error code if the specified font is invalid. If you register a user-supplied font. printf("Press any key to halt:"). By using the name of a linked-in font in a call to registerbgifont. if the code is valid. 0. /* terminate with an error code */ } /* draw a line */ line(0. grapherrormsg(errorcode)). getch(). it registers the code in internal tables. This routine checks the linked-in code for the specified font.h> #include <stdlib. See also graphresult initgraph installuserdriver registerbgidriver settextstyle Example /* registerbgifont example */ #include <graphics.h> int registerbgifont(void (*font)(void)). getmaxy()).h> #include <stdio.h> #include <conio. exit(1). Description Calling registerbgifont informs the graphics system that the font pointed to by font was included at link time. } registerbgifont Syntax #include <graphics. closegraph(). if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". you must pass the result of registerbgifont to settextstyle as the font number to be used.h> . /* clean up */ getch(). Otherwise. getmaxx(). return 0. registerbgifont returns the font number of the registered font.

outtextxy(midx. HORIZ_DIR. printf("Press any key to halt:").LIB */ errorcode = registerbgifont(triplex_font). ""). CENTER_TEXT). 4). you write a different "handler function" to handle each different . /* terminate with an error code */ } /* initialize graphics and local variables */ initgraph(&gdriver. if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". return 0. exit(1). &gmode. int midx. /* read result of initialization */ errorcode = graphresult(). /* register a font file that was added into GRAPHICS. printf("Press any key to halt:"). In general. Description The registermousehandler function is available in the winbgim implementation of BGI graphics. closegraph(). exit(1). int)). gmode. /* clean up */ getch().h" void registermousehandler(int kind. midy. midy = getmaxy() / 2. } registermousehandler Syntax #include "winbgim. getch(). /* select the registered font */ settextstyle(TRIPLEX_FONT. midy. grapherrormsg(errorcode)). void h(int. /* output some text */ settextjustify(CENTER_TEXT. "The TRIPLEX FONT"). /* report any registration errors */ if (errorcode < 0) { printf("Graphics error: %s\n". int main(void) { /* request autodetection */ int gdriver = DETECT. grapherrormsg(errorcode)). errorcode. getch(). /* terminate with an error code */ } midx = getmaxx() / 2.

then the boolean // variable red_clicked is set to true.called whenever the middle mouse button is clicked down WM_MBUTTONUP . It checks copies the x. // and then return.called whenever the middle mouse button is double clicked WM_MBUTTONDOWN ..called whenever the left mouse button is released up WM_MBUTTONDBLCLK . The first argument to registermousehandler is one of these constants from the winbgim. If so...called whenever the right mouse button is released up The second argument to registermousehandler must be the name of the handler function that you wrote. your handler will be called and the two int parameters will be the x and y positions where the event happened..h file: WM_MOUSEMOVE if you want the handler called whenever the mouse moves WM_LBUTTONDBLCLK . int y) { if (getpixel(x.called whenever the right mouse button is double clicked WM_RBUTTONDOWN . I haven't yet tracked down the reason--it could be a broken mouse or it could be a bug in my programming. This function must be a void function with two int parameters.called whenever the middle mouse button is released up WM_RBUTTONDBLCLK .called whenever the right mouse button is clicked down WM_RBUTTONUP . } // Call this function to draw an isosoles triangle with the given base and ...y) == RED) red_clicked = true.. Whenever the specified mouse event occurs.y coordinates of the click to // see if the click was on a red pixel... Return Value None. The middle mouse button handlers aren't working on my machine. If they need to do more than a little // work.h" // The click_handler will be called whenever the left mouse button is // clicked.called whenever the left mouse button is clicked down WM_LBUTTONUP .. kind of mouse event. See also mousex mousey Example /* mouse example */ #include "winbgim... they should set a variable that will trigger the work going. Note that in general // all handlers should be quick.called whenever the left mouse button is double clicked WM_LBUTTONDOWN .. bool red_clicked = false.... void click_handler(int x.. and you "register" each of your handlers by calling registermousehandler..

base/2. // Divisor for the length of a triangle side // Put the machine into graphics mode and get the maximum coordinates: initwindow(450. "Left click in RED to end. setcolor(WHITE). line(maxx/2 .10 . maxy = getmaxy( ). void triangle(int base.h> . divisor = 2. // Register the function that handles a left mouse click registermousehandler(WM_LBUTTONDOWN. maxx/2 + base/2. 2). RED). outtextxy(20. maxy. 300). fillellipse(maxx/2. The triangle will be drawn just above the botton of the screen. line(maxx/2 . cout << "x=" << mousex( ). red_clicked = false.base/2. maxy .10. maxy . 20.10). maxy . maxy . // height. maxx/2. 50). HORIZ_DIR. } restorecrtmode Syntax #include <graphics.height).10.10.height). // Print a message and wait for a red pixel to be double clicked: settextstyle(DEFAULT_FONT. // Maximum x and y pixel coordinates int divisor. // Switch back to text mode: closegraph( ). click_handler). maxy . divisor++. 50. maxy/divisor). while (!red_clicked) { triangle(maxx/divisor. int maxy = getmaxy( ). // Draw a white circle with red inside and a radius of 50 pixels: setfillstyle(SOLID_FILL. maxy/2. delay(500). setcolor(BLUE). maxy . maxx/2. line(maxx/2 + base/2. maxx = getmaxx( ). } cout << "The mouse was clicked at: ".10 . cout << " y=" << mousey( ) << endl. } void main(void) { int maxx. int height) { int maxx = getmaxx( ).").

exit(1). /* restore system to text mode */ restorecrtmode(). Windows Notes restorecrtmode is implemented in winbgim. y.h> #include <stdio. int x.h> #include <conio.h> #include <stdlib. CENTER_TEXT). ""). getch(). See also getgraphmode initgraph setgraphmode Example /* restorecrtmode example */ #include <graphics. /* terminate with an error code */ } x = getmaxx() / 2. &gmode. y = getmaxy() / 2. textmode should not be used for this purpose. This is because both the graphics window and the text window are always open during any Windows program. This function can be used in conjunction with setgraphmode to switch back and forth between text and graphics modes. if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". y. to change to a different text mode. printf("Press any key to return to graphics mode:"). /* output a message */ settextjustify(CENTER_TEXT. but it does not do any work. printf("Press any key to halt:"). so there is no need to switch back and forth between the two modes. /* initialize graphics and local variables */ initgraph(&gdriver. getch(). getch(). /* read result of initialization */ errorcode = graphresult(). . Description restorecrtmode restores the original video mode detected by initgraph.h> int main(void) { /* request autodetection */ int gdriver = DETECT. outtextxy(x. errorcode. gmode. Return Value None. void restorecrtmode(void). "Press any key to exit graphics:").\n"). grapherrormsg(errorcode)). printf("We're now in text mode. use it only when the screen is in text mode.

Each of the r. // Change drawing color to BLUE. // Change palette entry 4 to BLUE. COLOR(9. outtextxy(x. closegraph(). y. /* output a message */ settextjustify(CENTER_TEXT. Three other macros (RED_VALUE. if (IS_RGB_COLOR(current)) // Check whether it is an RGB color. setpalette(4.g. if (IS_BGI_COLOR(current)) // Check whether it is a BGI color. COLOR(255. setcolor(COLOR(255.100. it may be used as an argument to any of the BGI functions that expect a color.b). BLUE). outtextxy(x. For example.0) is a mostly red color with some green and no blue.g. A color may be specified from red. The sixteen ordinary BGI colors. } Colors for Windows BGI The winbgim package supports two types of colors that may be used with any of the functions that expect colors as arguments: 1. DARKGRAY LIGHTBLUE LIGHTGREEN LIGHTCYAN 5. green and blue components using a new macro called COLOR(r. int current = getcolor( ). /* clean up */ getch(). /* return to graphics mode */ setgraphmode(getgraphmode()).0). If you create one of these colors. LIGHTRED LIGHTMAGENTA YELLOW WHITE 6. "We're back in graphics mode.// Change palette entry 4 to nearly black. // Change drawing color to reddish-green. y+textheight("W").9)). CENTER_TEXT). GREEN_VALUE. setpalette(4. These colors may also be returned from BGI functions such as getbkcolor. IS_BGI_COLOR and IS_RGB_COLOR) are explained in the examples below.100. cout << "Current RGB drawing color has these components:\n" << "Red: " << RED_VALUE(current) << '\n' << "Green: " << GREEN_VALUE(current) << '\n' << "Blue: " << BLUE_VALUE(current) << '\n' ."). // Set current to current drawing color.b arguments must be a number in the range 0 to 255. BLUE_VALUE. "Press any key to halt:"). BLACK BLUE GREEN CYAN 3. RED MAGENTA BROWN LIGHTGRAY 4. cout << "Current BGI drawing color is: " << current << end. RGB Examples: #include "winbgim. These are the integers 0 through 15 or you may use the symbolic names: 2. return 0.h" setcolor(BLUE).9.

h> void sector(int x. i. midy.h< #include <stdio. int midx. and drawing from stangle to endangle. See also arc circle ellipse getarccoords getaspectratio graphresult pieslice setfillpattern setfillstyle setgraphbufsize Example /* sector example */ #include <graphics. The pie slice is outlined using the current color. . int stangle. gmode. int yradius). int xradius. They are measured counter-clockwise with 0 degrees at 3 o'clock. endangle = 135. &gmode. Return Value None. grapherrormsg(errorcode)). /* initialize graphics and local variables */ initgraph(&gdriver. Description Draws and fills an elliptical pie slice using (x. int xrad = 100. xradius and yradius as the horizontal and vertical radii. int endangle. ""). respectively. if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". and filled using the pattern and color defined by setfillstyle or setfillpattern. int y.h< int main(void) { /* request autodetection */ int gdriver = DETECT. The angles for sector are given in degrees. If an error occurs while the pie slice is filling. 90 degrees at 12 o'clock. int stangle = 45.y) as the center point.h< #include <stdlib.h< #include <conio. errorcode.sector Syntax #include <graphics. /* read result of initialization */ errorcode = graphresult(). getch(). and so on. graphresult returns a value of -6 (grNoScanMem). yrad = 50. printf("Press any key to halt:").

} /* clean up */ closegraph(). VGA. int x.h> #include <stdio. ht. errorcode. depending on how many graphics pages are available on your system. See also setvisualpage Example /* setactivepage example */ #include <graphics. } setactivepage Syntax #include <graphics. i<USER_FILL. . endangle.h> void setactivepage(int page).h> int main(void) { /* select driver and mode that supports multiple pages */ int gdriver = EGA. All subsequent graphics output will be directed to that graphics page. midy = getmaxy() / 2. gmode = EGAHI. ""). i++) { /* set the fill style */ setfillstyle(i. and Hercules graphics cards support multiple pages. getch(). &gmode. y. Description setactivepage makes page the active graphics page. Return Value None. /* terminate with an error code */ } midx = getmaxx() / 2. midy. return 0. Only the EGA. stangle.h> #include <stdlib. yrad). /* initialize graphics and local variables */ initgraph(&gdriver. getmaxcolor()). /* loop through the fill patterns */ for (i=EMPTY_FILL. xrad. /* draw the sector slice */ sector(midx. The active graphics page might not be the one you see onscreen. exit(1).h> #include <conio.

/* clean up */ getch(). getmaxx(). /* read result of initialization */ errorcode = graphresult(). getmaxy()). "Press any key to view page #1:"). You can partially (or completely) change the colors in the EGA/VGA palette with setallpalette. return 0. "This is page #1:"). ht = textheight("W"). /* select the off screen page for drawing */ setactivepage(1). /* select page #1 as the visible page */ setvisualpage(1). if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n". } setallpalette Syntax #include <graphics. getch(). y. closegraph(). "Press any key to halt:"). y. 0. printf("Press any key to halt:"). /* terminate with an error code */ } x = getmaxx() / 2. Description setallpalette sets the current palette to the values given in the palettetype structure pointed to by palette. grapherrormsg(errorcode)). y = getmaxy() / 2. /* output a message on page #0 */ outtextxy(x. "This is page #0. getch(). /* output a message on page #1 */ settextjustify(CENTER_TEXT. outtextxy(x.h> void setallpalette(struct palettetype *palette). /* draw a line on page #1 */ line(0. /* select drawing to page #0 */ setactivepage(0). outtextxy(x. outtextxy(x. CENTER_TEXT)."). y+ht. The MAXCOLORS constant and the palettetype structure used by setallpalette are defined in graphics. y+ht.h as follows: #define MAXCOLORS 15 . exit(1).

If an element of colors is -1. and the current palette remains unchanged. colors is an array of size bytes containing the actual raw color numbers for each entry in the palette. graphresult returns -11 (grError). Note: Valid colors depend on the current graphics driver and current graphics mode. . The elements in the colors array used by setallpalette can be represented by symbolic constants which are defined in graphics. setallpalette cannot be used with the IBM-8514 driver. signed char colors[MAXCOLORS + 1]. See Actual Color Table given here: Name Value BLACK 0 BLUE 1 GREEN 2 CYAN 3 RED 4 MAGENTA 5 BROWN 6 LIGHTGRAY 7 DARKGRAY 8 LIGHTBLUE 9 LIGHTGREEN 10 LIGHTCYAN 11 LIGHTRED 12 LIGHTMAGENTA 13 YELLOW 14 WHITE 15 EGA_BROWN 20 EGA_DARKGRAY 56 EGA_LIGHTBLUE 57 EGA_LIGHTGREEN 58 EGA_LIGHTCYAN 59 EGA_LIGHTRED 60 EGA_LIGHTMAGENTA 61 EGA_YELLOW 62 EGA_WHITE 63 Changes made to the palette are seen immediately onscreen. Each time a palette color is changed. struct palettetype { unsigned char size. }. size gives the number of colors in the palette for the current graphics driver in the current mode. the palette color for that entry is not changed. Return Value If invalid input is passed to setallpalette.h. all occurrences of that color onscreen change to the new color value.

maxcolor. printf("Press any key to halt:"). Currently drawn pixels do not change their color when the palette changes (no "palette animation"). See also getpalette getpalettesize graphresult setbkcolor setcolor setpalette Example See also getpalette getpalettesize graphresult setbkcolor setcolor setpalette Example /* setallpalette example */ #include <graphics. /* read result of initialization */ errorcode = graphresult(). /* terminate with an error code */ } maxcolor = getmaxcolor(). ht. If you want to set a palette color to an RGB color. if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n". int color. /* initialize graphics and local variables */ initgraph(&gdriver.h> #include <stdlib.h> #include <conio. In the windows version. ""). struct palettetype pal. getch(). then use setrgbpalette.h> #include <stdio. int y = 10. char msg[80].Windows Notes The winbgim version of setallpalette expects a palettetype object of up to 16 colors. . changing the palette effects only future drawing. errorcode. gmode.h> int main(void) { /* request autodetection */ int gdriver = DETECT. exit(1). Each color is one of the 16 BGI color numbers (0 through 15). grapherrormsg(errorcode)). &gmode.

getch(). Return Value None. call getaspectratio. color<=maxcolor. You could correct this in the hardware by realigning the monitor. Description setaspectratio changes the default aspect ratio of the graphics system. outtextxy(1. color++) { setcolor(color). If circles appear elliptical. int yasp). } /* wait for a key */ getch(). y. /* black out the colors one by one */ for (color=1. color++) { setpalette(color. the monitor is not aligned properly. return 0. } setaspectratio Syntax #include <graphics. BLACK). The graphics system uses the aspect ratio to make sure that circles are round onscreen. ht = 2 * textheight("W"). /* display the default palette colors */ for (color=1. y += ht. /* clean up */ getch(). "Color: %d". See also circle getaspectratio Example /* setaspectratio example */ #include <graphics. /* grab a copy of the palette */ getpalette(&pal). msg).h> .h> void setaspectratio(int xasp. To obtain the current aspect ratio from the system. color<=maxcolor. sprintf(msg. but it's easier to change in the software by using setaspectratio to set the aspect ratio. closegraph(). color). } /* restore the palette colors */ setallpalette(&pal).

h> #include <conio. closegraph(). getch(). circle(midx. if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n". return 0. /* clean up */ getch(). midy = getmaxy() / 2. yasp). /* adjust the aspect for a narrow circle */ cleardevice(). yasp/2). /* terminate with an error code */ } midx = getmaxx() / 2. &gmode. ""). midx. grapherrormsg(errorcode)). /* clear the screen */ cleardevice(). &yasp). getch(). 100).h> #include <stdio. midy. /* initialize graphics and local variables */ initgraph(&gdriver. setcolor(getmaxcolor()). errorcode. int xasp. 100). midy. exit(1). /* get current aspect ratio settings */ getaspectratio(&xasp. /* adjust the aspect for a wide circle */ setaspectratio(xasp/2. midy.h> int main(void) { /* request autodetection */ int gdriver = DETECT. } setbkcolor . midy. circle(midx. gmode. /* draw normal circle */ circle(midx. getch(). #include <stdlib. 100). printf("Press any key to halt:"). /* read result of initialization */ errorcode = graphresult(). yasp. setaspectratio(xasp.

you can call setbkcolor(BLUE) /* or */ setbkcolor(1) On CGA and EGA systems. and you change the palette colors with setpalette or setallpalette. If you use an EGA or a VGA. only future drawing will use the new background color (anything currently drawn in the old background color will stay in the old color). setbkcolor changes the background color by changing the first entry in the palette. Description setbkcolor sets the background to the color specified by color. Windows Notes The winbgim version allows the color argument to be an ordinary BGI color (from 0 to 15) or an RGB color. if you want to set the background color to blue. Calling setbkcolor(0) will change the background color to the current color at index [0] of the palette (rather than always changing the background to black). This is because the parameter to setbkcolor indicates the entry number in the current palette rather than a specific color (unless the parameter passed is 0.h> void setbkcolor(int color). The argument color can be a name or a number as listed below. Also. (These symbolic names are defined in graphics.h. which always sets the background color to black).) Name Value BLACK 0 BLUE 1 GREEN 2 CYAN 3 RED 4 MAGENTA 5 BROWN 6 LIGHTGRAY 7 DARKGRAY 8 LIGHTBLUE 9 LIGHTGREEN 10 LIGHTCYAN 11 LIGHTRED 12 LIGHTMAGENTA 13 YELLOW 14 WHITE 15 For example. Return Value None.Syntax #include <graphics. the defined symbolic constants might not give you the correct color. See also getbkcolor setallpalette setcolor setpalette .

bkcol<=maxcolor.h> #include <conio. y = getmaxy() / 2. /* output a messsage */ if (bkcol == WHITE) setcolor(EGA_BLUE). outtextxy(x. ""). sprintf(msg. char msg[80]. bkcol). } /* clean up */ closegraph(). &gmode. /* initialize graphics and local variables */ initgraph(&gdriver. errorcode. y. msg). gmode = EGAHI.h> #include <stdio. x. if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". /* terminate with an error code */ } /* maximum color index supported */ maxcolor = getmaxcolor(). y. /* for centering text messages */ settextjustify(CENTER_TEXT. return 0. /* select a new background color */ setbkcolor(bkcol).h> #include <stdlib. getch(). bkcol++) { /* clear the screen */ cleardevice(). /* read result of initialization */ errorcode = graphresult(). int bkcol. CENTER_TEXT).Example /* setbkcolor example */ #include <graphics. printf("Press any key to halt:"). /* loop through the available colors */ for (bkcol=0. "Background color: %d". } .h> int main(void) { /* _select driver and mode that supports multiple background colors*/ int gdriver = EGA. x = getmaxx() / 2. grapherrormsg(errorcode)). getch(). exit(1). maxcolor.

Return Value None. The drawing colors shown below are available for the CGA and EGA. Description setcolor sets the current drawing color to color. In this mode. light green. either setcolor(3) or setcolor(CGA_YELLOW) selects a drawing color of yellow. and yellow. in CGAC0 mode. and so on are drawn.setcolor Syntax #include <graphics. Palette Number Three Colors 0 LIGHTGREEN LIGHTRED YELLOW 1 LIGHTCYAN LIGHTMAGENTA WHITE 2 GREEN RED BROWN 3 CYAN MAGENTA LIGHTGRAY Name Value BLACK 0 BLUE 1 GREEN 2 CYAN 3 RED 4 MAGENTA 5 BROWN 6 LIGHTGRAY 7 DARKGRAY 8 LIGHTBLUE 9 LIGHTGREEN 10 LIGHTCYAN 11 LIGHTRED 12 LIGHTMAGENTA 13 YELLOW 14 WHITE 15 You select a drawing color by passing either the color number itself or the equivalent symbolic name to setcolor.h> void setcolor(int color). The current drawing color is the value to which pixels are set when lines. respectively. For example. See also getcolor getmaxcolor . Windows Notes The winbgim version allows the color argument to be an ordinary BGI color (from 0 to 15) or an RGB color. the palette contains four colors: the background color. which can range from 0 to getmaxcolor. light red.

/* loop through the available colors */ for (color=1. /* read result of initialization */ errorcode = graphresult().h> #include <stdio. maxcolor. errorcode. if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n". } . msg). gmode = EGAHI. return 0. "Color: %d". y = getmaxy() / 2. /* initialize graphics and local variables */ initgraph(&gdriver. CENTER_TEXT). y. int color. /* clear the screen */ setcolor(color). y. outtextxy(x. &gmode. exit(1). char msg[80]. color). /* terminate with an error code */ } /* maximum color index supported */ maxcolor = getmaxcolor(). color++) { cleardevice(). graphresult setallpalette setbkcolor setpalette Example /* setcolor example */ #include <graphics. } /* clean up */ closegraph(). grapherrormsg(errorcode)). ""). color<=maxcolor.h> int main(void) { /* select driver and mode that supports multiple drawing colors */ int gdriver = EGA. /* select new background color */ /* output a messsage */ sprintf(msg. getch(). getch().h> #include <stdlib. /* for centering text messages */ settextjustify(CENTER_TEXT. x. x = getmaxx() / 2.h> #include <conio. printf("Press any key to halt:").

maxy. if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n". int maxx.h> void setfillpattern(char *upattern. 0x20. See also getfillpattern getfillsettings graphresult sector setfillstyle Example /* setfillpattern example */ #include <graphics. 0x24. 0x24. 0x27. int color). exit(1). &gmode. grapherrormsg(errorcode)). /* terminate with an error code */ } maxx = getmaxx(). Windows Notes The winbgim version allows the color argument to be an ordinary BGI color (from 0 to 15) or an RGB color. /* a user-defined fill pattern */ char pattern[8] = {0x00. 0x07.h> int main(void) { /* request autodetection */ int gdriver = DETECT.setfillpattern Syntax #include <graphics. 0x00}. Description setfillpattern is like setfillstyle. printf("Press any key to halt:"). errorcode.h> #include <conio. the corresponding pixel is plotted. gmode. with each byte corresponding to 8 pixels in the pattern. Return Value None. except that you use it to set a user-defined 8x8 pattern rather than a predefined pattern.h> #include <stdio. upattern is a pointer to a sequence of 8 bytes. ""). /* initialize graphics and local variables */ initgraph(&gdriver. getch(). /* read result of initialization */ errorcode = graphresult(). . 0x70.h> #include <stdlib. Whenever a bit in a pattern byte is set to 1.

h> #include <stdlib.h> /* the names of the fill styles supported */ . instead.h> #include <conio. int color). maxy = getmaxy(). To set a user-defined fill pattern. and the current fill pattern and fill color remain unchanged. maxy). closegraph(). maxx. do not give a pattern of 12 (USER_FILL) to setfillstyle. See also bar bar3d fillpoly floodfill getfillsettings graphresult pieslice sector setfillpattern Example /* setfillstyle example */ #include <graphics.h> #include <string. /* fill the screen with the pattern */ bar(0. /* select a user-defined fill pattern */ setfillpattern(pattern. 0. return 0.h> void setfillstyle(int pattern. setcolor(getmaxcolor()). Return Value None. If invalid input is passed to setfillstyle. Windows Notes The winbgim version allows the color argument to be an ordinary BGI color (from 0 to 15) or an RGB color. } setfillstyle Syntax #include <graphics. graphresult returns -1(grError). Description setfillstyle sets the current fill pattern and fill color. getmaxcolor()). /* clean up */ getch().h> #include <stdio. call setfillpattern.

return 0. midy. /* terminate with an error code */ } midx = getmaxx() / 2. printf("Press any key to halt:"). errorcode. "LINE_FILL". if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". stylestr). char *fname[] = { "EMPTY_FILL". 0. closegraph(). gmode. /* read result of initialization */ errorcode = graphresult(). 0). char stylestr[40]. &gmode. int main(void) { /* request autodetection */ int gdriver = DETECT. midx-10. getch(). "WIDE_DOT_FILL". fname[style]). style++) { /* select the fill style */ setfillstyle(style. "SOLID_FILL". midx. getmaxcolor()). int style. } setgraphbufsize . /* output a message */ outtextxy(midx. "HATCH_FILL". cleardevice(). } /* clean up */ getch(). "XHATCH_FILL". /* fill a bar */ bar3d(0. midy. grapherrormsg(errorcode)). "INTERLEAVE_FILL". "SLASH_FILL". midy = getmaxy() / 2. exit(1). style < USER_FILL. midy. "USER_FILL" }. /* initialize graphics and local variables */ initgraph(&gdriver. ""). /* wait for a key */ getch(). "CLOSE_DOT_FILL". "BKSLASH_FILL". "LTSLASH_FILL". 0. "LTBKSLASH_FILL". /* convert style into a string */ strcpy(stylestr. for (style = EMPTY_FILL.

The default size of this buffer. See also closegraph initgraph sector Example /* setgraphbufsize example */ #include <graphics.h> #include <stdlib. is 4. exit(1). char msg[80]. You must call setgraphbufsize before calling initgraph.096 bytes. Once initgraph has been called. /* read result of initialization */ errorcode = graphresult(). Description Some of the graphics routines (such as floodfill) use a memory buffer that is allocated when initgraph is called and released when closegraph is called. /* terminate with an error code */ } x = getmaxx() / 2. /* _set size of internal graphics buffer before calling initgraph */ oldsize = setgraphbufsize(BUFSIZE). if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n".h> #include <stdio. all calls to setgraphbufsize are ignored until after the next call to closegraph.h> #include <conio. y. . You might want to make this buffer smaller (to save memory space) or bigger (if. Return Value setgraphbufsize returns the previous size of the internal buffer. setgraphbufsize tells initgraph how much memory to allocate for this internal graphics buffer when it calls _graphgetmem. errorcode. int x. Windows Notes setgraphbufsize is not available in the winbgim implementation.h> unsigned setgraphbufsize(unsigned bufsize). a call to floodfill produces error -7: Out of flood memory).Syntax #include <graphics. grapherrormsg(errorcode)). for example. oldsize. gmode. /* initialize graphics and local variables */ initgraph(&gdriver.h> #define BUFSIZE 1000 /* internal graphics buffer size */ int main(void) { /* request autodetection */ int gdriver = DETECT. &gmode. allocated by _graphgetmem. ""). printf("Press any key to halt:"). getch().

This is because both the graphics window and the text window are always open during any Windows program. msg). Windows Notes setgraphmode is implemented in winbgim. setgraphmode clears the screen and resets all graphics settings to their defaults (current position. CENTER_TEXT). but it does not do any work. and so on). but it does not do any work. "Old graphics buffer size: %d". Windows Notes setgraphmode is implemented in winbgim. y = getmaxy() / 2. oldsize). } setgraphmode Syntax #include <graphics. Description setgraphmode selects a graphics mode different than the default one set by initgraph. outtextxy(x. Return Value If you give setgraphmode an invalid mode for the current device driver. BUFSIZE).h> #include <conio.h> void setgraphmode(int mode).h> . "Graphics buffer size: %d". settextjustify(CENTER_TEXT. color. outtextxy(x. See also getgraphmode getmoderange graphresult initgraph restorecrtmode Example /* setgraphmode example */ #include <graphics. closegraph(). /* clean up */ getch(). msg). so there is no need to switch back and forth between the two modes. graphresult returns a value of -10 (grInvalidMode). palette. You can use setgraphmode in conjunction with restorecrtmode to switch back and forth between text and graphics modes.h> #include <stdlib. sprintf(msg.h> #include <stdio. /* output some messages */ sprintf(msg. y+textheight("W"). return 0. y. viewport. mode must be a valid mode for the current device driver.

getch(). y. y. /* initialize graphics and local variables */ initgraph(&gdriver. getch(). and so on. lineto. drawpoly. &gmode. int main(void) { /* request autodetection */ int gdriver = DETECT.\n"). y+textheight("W"). CENTER_TEXT). closegraph(). y. /* terminate with an error code */ } x = getmaxx() / 2. return 0. /* restore system to text mode */ restorecrtmode(). errorcode."). /* output a message */ settextjustify(CENTER_TEXT. printf("We're now in text mode. outtextxy(x. } setlinestyle Syntax #include <graphics. rectangle. printf("Press any key to return to graphics mode:"). "We're back in graphics mode. y = getmaxy() / 2. outtextxy(x. CENTER_TEXT). /* output a message */ settextjustify(CENTER_TEXT. unsigned upattern.h> void setlinestyle(int linestyle. if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". outtextxy(x. /* read result of initialization */ errorcode = graphresult(). "Press any key to exit graphics:"). gmode. /* clean up */ getch(). Description setlinestyle sets the style for all lines drawn by line. /* return to graphics mode */ setgraphmode(getgraphmode()). printf("Press any key to halt:"). exit(1). ""). int x. "Press any key to halt:"). getch(). grapherrormsg(errorcode)). int thickness). .

}.h. dotted. or pie slices. a solid line corresponds to a upattern of 0xFFFF (all pixels drawn). gives names to these operators: Name Value Description SOLID_LINE 0 Solid line DOTTED_LINE 1 Dotted line CENTER_LINE 2 Centered line DASHED_LINE 3 Dashed line USERBIT_LINE 4 User-defined line style thickness specifies whether the width of subsequent lines drawn will be normal or thick. you must still provide the upattern parameter. if it is not equal to 4). graphresult returns -11.h> . whenever a bit in the pattern word is 1. int thickness. Only the thickness parameter is used. unsigned upattern. In that case. Note: The linestyle parameter does not affect arcs. Return Value If invalid input is passed to setlinestyle. Name Value Description NORM_WIDTH 1 1 pixel wide THICK_WIDTH 3 3 pixels wide upattern is a 16-bit pattern that applies only if linestyle is USERBIT_LINE (4). and the current line style remains unchanged. For example. the corresponding pixel in the line is drawn in the current drawing color. linestyle specifies in which of several styles subsequent lines will be drawn (such as solid. circles. The enumeration line_styles.h as follows: struct linesettingstype { int linestyle. dashed). which is defined in graphics. ellipses. The linesettingstype structure is defined in graphics. See also arc bar3d bar circle drawpoly ellipse getlinesettings graphresult line linerel lineto pieslice rectangle Example /* setlinestyle example */ #include <graphics. If the linestyle parameter to setlinestyle is not USERBIT_LINE (in other words. but it will be ignored. centered. and a dashed line can correspond to a upattern of 0x3333 or 0x0F0F.

userpat. 1). "CENTER_LINE". for (style=SOLID_LINE. midy). /* draw a rectangle */ rectangle(0. . /* terminate with an error code */ } midx = getmaxx() / 2.h> #include <string. ""). gmode. /* read result of initialization */ errorcode = graphresult(). userpat.h> /* the names of the line styles supported */ char *lname[] = { "SOLID_LINE". getmaxx(). errorcode. getmaxy()). 0. /* initialize graphics and local variables */ initgraph(&gdriver. midy = getmaxy() / 2.h> #include <stdio. grapherrormsg(errorcode)). lname[style]). midx-10. "DOTTED_LINE". stylestr). /* draw a line */ line(0.#include <stdlib. } /* clean up */ closegraph(). "USERBIT_LINE" }. /* output a message */ outtextxy(midx. exit(1). style++) { /* select the line style */ setlinestyle(style. /* wait for a key */ getch(). getch(). cleardevice(). /* convert style into a string */ strcpy(stylestr. char stylestr[40]. /* a user-defined line pattern */ /* binary: "0000000000000001" */ userpat = 1. printf("Press any key to halt:").h> #include <conio. if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". style<=USERBIT_LINE. int style. midy. midy. &gmode. 0. int main(void) { /* request autodetection */ int gdriver = DETECT. midx. "DASHED_LINE".

return 0. You can partially (or completely) change the colors in the EGA/VGA palette with setpalette. For example.h> void setpalette(int colornum.5) changes the first color in the current palette (the background color) to actual color number 5. you can only change the first entry in the palette (colornum equals 0. The color parameter passed to setpalette can be represented by symbolic constants which are defined in graphics. the background color) with a call to setpalette. and the current palette remains unchanged. int color).1). The colornum should be a palette index from 0 to 15. use setrgbpalette instead. On a CGA.h. graphresult returns -11. Name Value BLACK 0 BLUE 1 GREEN 2 CYAN 3 RED 4 MAGENTA 5 BROWN 6 LIGHTGRAY 7 DARKGRAY 8 LIGHTBLUE 9 LIGHTGREEN 10 LIGHTCYAN 11 LIGHTRED 12 LIGHTMAGENTA 13 YELLOW 14 WHITE 15 setpalette cannot be used with the IBM-8514 driver. Windows Notes The winbgim version allows the color argument to be an ordinary BGI color (from 0 to 15) or an RGB color. setpalette(0. Description setpalette changes the colornum entry in the palette to color. . Return Value If invalid input is passed to setpalette. If size is the number of entries in the current palette. colornum can range between 0 and (size . } setpalette Syntax #include <graphics.

printf("Press any key to halt:"). "Color: %d". maxcolor. /* initialize graphics and local variables */ initgraph(&gdriver. if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". Currently drawn pixels do not change their color when the palette changes (no "palette animation"). In the windows version.h> #include <stdio.h> int main(void) { /* request autodetection */ int gdriver = DETECT. /* terminate with an error code */ } maxcolor = getmaxcolor(). color<=maxcolor. } /* wait for a key */ getch(). "").h> #include <stdlib. getch(). } . int color. errorcode. color++) { setcolor(color). outtextxy(1. /* read result of initialization */ errorcode = graphresult(). ht = 2 * textheight("W"). int y = 10. } /* clean up */ closegraph(). msg). &gmode. exit(1). /* display the default colors */ for (color=1. return 0. color). char msg[80]. /* black out the colors one by one */ for (color=1. y. color<=maxcolor. y += ht. color++) { setpalette(color.h> #include <conio. getch(). grapherrormsg(errorcode)). BLACK). sprintf(msg. changing the palette effects only future drawing. gmode. ht. See also setrgbpalette Example /* setpalette example */ #include <graphics.

colornum is in the range 0 to 255.h> void setrgbpalette(int colornum. &gmode.h> #include <stdio. and out of each byte. For compatibility with other IBM graphics adapters. /* initialize graphics and local variables */ initgraph(&gdriver. Currently drawn pixels do not change their color when the palette changes (no "palette animation"). or they can be changed using setrgbpalette. Only the lower byte of red. colornum is in the range 0 to 15. colornum defines the palette entry to be loaded. or blue is used. . However. r. and blue define the component colors of the palette entry. For the IBM 8514 display (and the VGA in 256K color mode). These values can be used as is. changing the palette effects only future drawing. In the windows version. y. color argument to be an ordinary BGI color (from 0 to 15) or an RGB color.h> int main(void) { /* select driver and mode that supports use of setrgbpalette */ int gdriver = VGA. ""). while red. int blue). int i. COLOR(r. green.h> #include <conio. g and b. is similar to setpalette(colornum. green. The difference is that setrgbpalette will use only the six most significant bits of the least significant byte of r. int green. b). only the 6 most significant bits are loaded in the palette. int red. Windows Notes The winbgim version allows the the colornum to be a palette index from 0 to 15. For the remaining modes of the VGA. COLOR(r. gmode = VGAHI. errorcode. See also setpalette Example /* setrgbpalette example */ #include <graphics. xmax.g. struct palettetype pal. the BGI driver defines the first 16 palette entries of the IBM 8514 to the default colors of the EGA/VGA. Description setrgbpalette can be used with the IBM 8514 and VGA drivers. The call setrgbpalette(colornum.setrgbpalette Syntax #include <graphics.g. g. ht.h> #include <stdlib. Return Value None.b) uses the entire least significant byte of r. g and b.b) ).

getch(). } /* clean up */ getch(). printf("Press any key to halt:"). int blue). y += ht. colornum is in the range 0 to 15.colors[i]. } setrgbpalette Syntax #include <graphics. Return Value None. These values can be used as is. xmax = getmaxx(). /* read result of initialization */ errorcode = graphresult(). /* create gray scale */ for (i=0. Only the lower byte of red. only the 6 most significant bits are loaded in the palette. i<pal. i*4. i*4. while red. and out of each byte. For the remaining modes of the VGA.h> void setrgbpalette(int colornum. for (i=0. the BGI driver defines the first 16 palette entries of the IBM 8514 to the default colors of the EGA/VGA. exit(1). y. closegraph(). colornum is in the range 0 to 255. grapherrormsg(errorcode)). bar(0. i++) setrgbpalette(pal. or blue is used. . green. i).size. int red. y = 0. green. i<pal. /* display the gray scale */ ht = getmaxy() / 16. int green.size. i++) { setfillstyle(SOLID_FILL. /* terminate with an error code */ } /* grab a copy of the palette */ getpalette(&pal). For the IBM 8514 display (and the VGA in 256K color mode). xmax. y+ht). return 0. colornum defines the palette entry to be loaded. and blue define the component colors of the palette entry. if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". i*4). or they can be changed using setrgbpalette. Description setrgbpalette can be used with the IBM 8514 and VGA drivers. For compatibility with other IBM graphics adapters.

i). /* initialize graphics and local variables */ initgraph(&gdriver. i<pal.g. i*4. getch().b) uses the entire least significant byte of r. grapherrormsg(errorcode)). The call setrgbpalette(colornum.h> int main(void) { /* select driver and mode that supports use of setrgbpalette */ int gdriver = VGA.size. for (i=0. color argument to be an ordinary BGI color (from 0 to 15) or an RGB color. However. changing the palette effects only future drawing. /* display the gray scale */ ht = getmaxy() / 16. The difference is that setrgbpalette will use only the six most significant bits of the least significant byte of r. b). See also setpalette Example /* setrgbpalette example */ #include <graphics. is similar to setpalette(colornum. gmode = VGAHI. In the windows version. g and b. i*4. ""). i++) { setfillstyle(SOLID_FILL. ht. xmax.colors[i]. exit(1). struct palettetype pal. .Windows Notes The winbgim version allows the the colornum to be a palette index from 0 to 15. g and b. /* create gray scale */ for (i=0. printf("Press any key to halt:"). if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". &gmode. /* terminate with an error code */ } /* grab a copy of the palette */ getpalette(&pal). r.h> #include <stdlib. i++) setrgbpalette(pal. COLOR(r. int i.h> #include <conio. y.g. /* read result of initialization */ errorcode = graphresult().b) ). xmax = getmaxx().h> #include <stdio. i*4). COLOR(r. y = 0. Currently drawn pixels do not change their color when the palette changes (no "palette animation").size. g. errorcode. i<pal.

closegraph(). Do this by converting them into object files with the BGIOBJ utility. it can affect bit-mapped or stroked characters. A charsize value of 0 can be used only with stroked fonts. int direction. The size of each character can be magnified using the charsize factor. The parameters font. the direction in which text is displayed. y += ht. and charsize passed to settextstyle are described in the following: font: One 8x8 bit-mapped font and several "stroked" fonts are available. } settextstyle Syntax #include <graphics. and the size of the characters. The enumeration font_names. the corresponding *. . bar(0. you can link font files into your program. If charsize is nonzero. then registering them through registerbgifont. } /* clean up */ getch(). The default direction is HORIZ_DIR. The 8x8 bit- mapped font is the default.h> void settextstyle(int font. A call to settextstyle affects all text output by outtext and outtextxy. provides names for these different font settings: Name Value Description DEFAULT_FONT 0 8x8 bit-mapped font TRIPLEX_FONT 1 Stroked triplex font SMALL_FONT 2 Stroked small font SANS_SERIF_FONT 3 Stroked sans-serif font GOTHIC_FONT 4 Stroked gothic font SCRIPT_FONT 5 Stroked script font SIMPLEX_FONT 6 Stroked triplex script font TRIPLEX_SCR_FONT 7 Stroked triplex script font COMPLEX_FONT 8 Stroked complex font EUROPEAN_FONT 9 Stroked European font BOLD_FONT 10 Stroked bold font The default bit-mapped font is built into the graphics system. To avoid this loading when several stroked fonts are used. direction. and only one at a time is kept in memory. which is defined in graphics. y. return 0.CHR file must be loaded from disk. xmax. direction: Font directions supported are horizontal text (left to right) and vertical text (rotated 90 degrees counterclockwise).h. y+ht). int charsize). when you select a stroked font (different from the last selected stroked font). Stroked fonts are stored in *. Therefore. Description settextstyle sets the text font.CHR disk files.

. gmode. ""). "BOLD font"}. midx. midy.h> /* the names of the text styles supported */ char *fname[] = { "DEFAULT font". if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". getch(). exit(1). outtext and outtextxy displays characters from the 8x8 bit- mapped font in an 8x8 pixel rectangle onscreen. "EUROPEAN font". /* terminate with an error code */ } midx = getmaxx() / 2. int style.h> #include <stdio. "TRIPLEX font". Always use textheight and textwidth to determine the actual dimensions of the text.h> #include <stdlib. these output functions display characters from the 8x8 bit- mapped font in a 16*16 pixel rectangle. &gmode. errorcode. "SCRIPT font". • When charsize equals 0. "GOTHIC_font". printf("Press any key to halt:"). • If charsize equals 2. /* read result of initialization */ errorcode = graphresult(). "TRIPLEX SCRIPT font". "SANS SERIF_font". "SMALL font". "SIMPLEX font".h> #include <conio. "COMPLEX font". Return Value See also gettextsettings graphresults installuserfont settextjustify setusercharsize textheight textwidth Example /* settextstyle example */ #include <graphics. /* initialize graphics and local variables */ initgraph(&gdriver. • If charsize equals 1. and so on (up to a limit of ten times the normal size). grapherrormsg(errorcode)). int size = 1. int main(void) { /* request autodetection */ int gdriver = DETECT. the output functions outtext and outtextxy magnify the stroked font text using either the default character magnification factor (4) or the user-defined character size given by setusercharsize.

See also gettextsettings graphresult settextstyle Example /* setusercharsize example */ #include <graphics. /* loop through the available text styles */ for (style=DEFAULT_FONT. settextjustify(CENTER_TEXT. divy = 2. midy. and the default height is scaled by multy : divy. For example. The values set by setusercharsize are active only if charsize equals 0. set multx = 2. The default width is scaled by multx : divx. } /* clean up */ closegraph(). multy = 3. style++) { cleardevice(). size). midy = getmaxy() / 2. to make text twice as wide and 50% taller than the default. as set by a previous call to settextstyle. &gmode. With setusercharsize. Return Value None.h> void setusercharsize(int multx. Description setusercharsize gives you finer control over the size of text from stroked fonts used with graphics functions.h> #include <conio. int multy. fname[style]). ""). CENTER_TEXT). errorcode. if (style == TRIPLEX_FONT) size = 4. int divx. /* select the text style */ settextstyle(style. style<=BOLD_FONT.h> #include <stdio. } setusercharsize Syntax #include <graphics. /* initialize graphics and local variables */ initgraph(&gdriver. getch(). return 0. /* output a message */ outtextxy(midx. int divy). gmode. HORIZ_DIR. .h> #include <stdlib. divx = 1.h> int main(void) { /* request autodetection */ int gdriver = DETECT. you specify factors by which the width and height are scaled.

getch(). 1. closegraph(). The current position (CP) is moved to (0. /* terminate with an error code */ } /* select a text style */ settextstyle(TRIPLEX_FONT. outtext("Wide"). /* output some normal text */ outtext("Norm "). /* make the text 1/3 the normal width */ setusercharsize(1. exit(1).top) and (right. /* read result of initialization */ errorcode = graphresult(). 1). HORIZ_DIR. If clip is nonzero.bottom).0) in the new window. /* make the text 3 times normal width */ setusercharsize(3. int top. The viewport corners are given in absolute screen coordinates by (left. 4). int bottom. int clip). /* move to the text starting position */ moveto(0. grapherrormsg(errorcode)). 3. return 0. Return Value If invalid input is passed to setviewport. 1. and the current view settings remain unchanged. /* clean up */ getch(). if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". getmaxy() / 2). The parameter clip determines whether drawings are clipped (truncated) at the current viewport boundaries. 1. See also clearviewport getviewsettings graphresult Example /* setviewport example */ #include <graphics.h> void setviewport(int left. printf("Press any key to halt:"). } setviewport Syntax #include <graphics. all drawings will be clipped to the current viewport. graphresult returns -11. Description setviewport establishes a new viewport for graphics output. 1). int right.h> . outtext("Short ").

#include <stdlib. grapherrormsg(errorcode)). 0) in default viewport"). return 0. "* <-. Description setvisualpage makes page the visual graphics page. /* message in default full-screen viewport */ outtextxy(0. Return Value None. 0. ""). 0) in smaller viewport"). 0.h> #define CLIP_ON 1 /* activates clipping in viewport */ int main(void) { /* request autodetection */ int gdriver = DETECT. /* terminate with an error code */ } setcolor(getmaxcolor()). CLIP_ON). &gmode. getmaxx()-50. See also graphresult .(0. gmode. errorcode. } setvisualpage Syntax #include <graphics. closegraph(). /* create a smaller viewport */ setviewport(50. getmaxy()-50. /* read result of initialization */ errorcode = graphresult(). /* initialize graphics and local variables */ initgraph(&gdriver.h> void setvisualpage(int page). "* <-. /* display some text */ outtextxy(0. /* clean up */ getch(). exit(1). 50.h> #include <conio. printf("Press any key to halt:").(0.h> #include <stdio. if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n". getch().

getch().h> int main(void) { /* select driver and mode that supports multiple pages */ int gdriver = EGA.h> #include <stdlib. return 0. /* initialize graphics and local variables */ initgraph(&gdriver. y. &gmode. ht = textheight("W"). "This is page #0. /* output a message on page #0 */ outtextxy(x. "This is page #1:"). /* clean up */ getch(). y+ht. /* output a message on page #1 */ settextjustify(CENTER_TEXT. ht. y. outtextxy(x. y. getch().h> #include <stdio. grapherrormsg(errorcode)). if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n". y+ht. errorcode. gmode = EGAHI. } . 0. /* select drawing to page #0 */ setactivepage(0). /* select the off screen page for drawing */ setactivepage(1)."). setactivepage Example /* setvisualpage example */ #include <graphics. /* select page #1 as the visible page */ setvisualpage(1). printf("Press any key to halt:"). "Press any key to halt:"). /* draw a line on page #1 */ line(0. outtextxy(x. /* terminate with an error code */ } x = getmaxx() / 2. "Press any key to view page #1:"). getmaxx(). ""). y = getmaxy() / 2.h> #include <conio. closegraph(). exit(1). getmaxy()). CENTER_TEXT). int x. outtextxy(x. /* read result of initialization */ errorcode = graphresult().

ymax = getmaxy(). xmax. Return Value None. See also lineto putimage Example /* setwritemode example */ #include <graphics. ymax). ymax. Two successive XOR commands will erase the line and restore the screen to its original appearance. /* initialize graphics and local variables */ initgraph(&gdriver. 0. /* draw a line */ line(0.h> #include <conio. "").h> #include <stdio. /* terminate with an error code */ } xmax = getmaxx(). COPY_PUT uses the assembly language MOV instruction. /* select XOR drawing mode */ setwritemode(XOR_PUT). lineto. rectangle. errorcode.h> void setwritemode(int mode). exit(1). gmode. and drawpoly. /* read result of initialization */ errorcode = graphresult().h> #include <stdlib. overwriting with the line whatever is on the screen. getch(). setwritemode currently works only with line. grapherrormsg(errorcode)). &gmode. int xmax. XOR_PUT uses the XOR command to combine the line with the screen. printf("Press any key to halt:"). linerel.setwritemode Syntax #include <graphics. . Description The following constants are defined: COPY_PUT = 0 /* MOV */ XOR_PUT = 1 /* XOR */ Each constant corresponds to a binary operation between each byte in the line and the corresponding bytes onscreen.h> int main() { /* request autodetection */ int gdriver = DETECT. if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n".

getch(). ymax). xmax. /* draw a line */ line(0. Description The graphics function textheight takes the current font size and multiplication factor. the string BorlandC++ is 8 pixels high. See also gettextsettings outtext outtextxy settextstyle textwidth Example /* textheight example */ #include <graphics. no source code modifications have to be made when different fonts are selected.h> int textheight(char *textstring). 0. For example. closegraph(). /* clean up */ getch(). Use textheight to compute the height of strings. and so on. and determines the height of textstring in pixels. This function is useful for adjusting the spacing between lines. /* select overwrite drawing mode */ setwritemode(COPY_PUT). sizing a title to make it fit on a graph or in a box. By using this function. 0.h> int main(void) { /* request autodetection */ .h> #include <stdio. } textheight Syntax #include <graphics. return 0. ymax). /* erase the line by drawing over it */ line(0. with the 8x8 bit-mapped font and a multiplication factor of 1 (set by settextstyle). Return Value textheight returns the text height in pixels. xmax. instead of doing the computations manually.h> #include <conio.h> #include <stdlib. computing viewport heights. getch().

and size */ settextstyle(TRIPLEX_FONT. HORIZ_DIR. y. closegraph(). exit(1). if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". Use textwidth to compute the width of strings. This function is useful for computing viewport widths. sizing a title to make it fit on a graph or in a box. /* output the message */ outtextxy(1. &gmode. and determines the width of textstring in pixels. Return Value textwidth returns the text width in pixels. instead of doing the computations manually. and multiplication factor. /* create a message string */ sprintf(msg. return 0. int y = 0. printf("Press any key to halt:"). grapherrormsg(errorcode)). getch(). direction. /* read result of initialization */ errorcode = graphresult(). } textwidth Syntax #include <graphics. "Size: %d". i). /* terminate with an error code */ } /* draw some text on the screen */ for (i=1. When you use this function. } /* clean up */ getch(). int gdriver = DETECT. and so on. i<11. i). msg). gmode. /* advance to the next text line */ y += textheight(msg). i++) { /* select the text style. no source code modifications have to be made when different fonts are selected. /* initialize graphics and local variables */ initgraph(&gdriver. Description The graphics function textwidth takes the string length. current font size. "").h> int textwidth(char *textstring). errorcode. See also gettextsettings . char msg[80]. int i.

for (i = 1.h> #include <stdio. grapherrormsg(errorcode)). getch(). exit(1). i). } . int x = 0.h> #include <stdlib. /* advance to the end of the text */ x += textwidth(msg). direction. errorcode. char msg[80]. &gmode. y = 0. printf("Press any key to halt:"). CENTER_TEXT). return 0. /* terminate with an error code */ } y = getmaxy() / 2. int i. settextjustify(LEFT_TEXT. ""). /* output the message */ outtextxy(x. closegraph(). i). if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n". msg). gmode. i++) { /* select the text style. "Size: %d". /* read result of initialization */ errorcode = graphresult(). /* create a message string */ sprintf(msg. and size */ settextstyle(TRIPLEX_FONT. outtext outtextxy settextstyle textheight Example /* textwidth example */ #include <graphics. } /* clean up */ getch(). y. HORIZ_DIR.h> #include <conio. i < 11.h> int main(void) { /* request autodetection */ int gdriver = DETECT. /* initialize graphics and local variables */ initgraph(&gdriver.

edu/~main/bgi/doc/bgi.colorado. any of the functions that use colors can use RGB colors in addition to the 16- color BGI palette.cs. . In this listing.html. Also.h. They are defined in graphics. the extra functions are indicated by . These extra functions are described in www. Using BGI with Windows The BGI graphics functions may also be used with Windows programs created by the Borland 5. Borland Graphics Interface (BGI) The following functions compose the Borland Graphics Interface and are usually available for 16 bit DOS applications.0 compiler or the free GNU C++ compiler. Use them to create onscreen graphics with text.