Create a Captcha with PHP

We’re going to learn how how CAPTCHA (CompletelyAutomated Public Turing test to tell Computers and Humans Apart) works and how it minimizes automatic sign-up of forms. We will also be creating a simple CAPTCHA script in PHP to illustrate this.

Basically CAPTCHA works in the following manner:

  1. Create Random Value: Some random string is generated, random values are often hard to guess and predict.
  2. Generate an Image: Images are used as these are generally a lot harder to read for computers while being nice and readable to humans. This is also the most important step as simple text in images can be read (and CAPTCHA cracked) quite easily. To make it difficult for them, developers employ different techniques so that the text in the image becomes hard to read for computers. Some create zig-zag lines for background while others twist-and-turn individual characters in the image. Possibilities are many and new techniques are being developed all the time as crackers are always into finding ways to break them.
  3. Store it: The random string generated (which is also in the image) is stored for matching the user input. The easiest way to do so is to use the Session variables.
  4. Matching: After the above step, the CAPTCHA image is generated and shown on some form which we want to protect from being abused. The users fills in the form along with the CAPTCHA text and submits it. Now we have the following:
    1. All submitted form data.
    2. CAPTCHA string (from form), input by user.
    3. CAPTCHA string (real one, generated by us), from session variable. Session variable is generally used as it can keep stored values across page requests. Here, we needed to preserve stored values from one page (form page) to another (action page-that receives form data).
  5. If both match, it’s okay otherwise not, in that case we can give the user a message that the CAPTCHA they had entered was wrong and their form could not be submitted. You could also ask them to verify it again.

The following image might illustrates this better:

CAPTCHA Generation and Matching

CAPTCHA Generation and Matching

From the above image it’s quite clear that when someone requests the form page, the CAPTCHA text is generated and sent back to requesting user, but only in the form of an image. If the requester is a human he’d not have much difficulty reading the image and inputting the text when asked but if it’s a bot it might face difficulties guessing whats in the image. In the next step when we match the string generated and the one the user had input, we can restrict automated form submissions.

The following is the code that does this, it’ll just output the CAPTCHA image to the browser when the script is requested:

QuickSort algorithm, code for Java, C++

Quicksort is a fast sorting algorithm, which is used not only for educational purposes, but widely applied in practice. On the average, it has O(n log n) complexity, making quicksort suitable for sorting big data volumes. The idea of the algorithm is quite simple and once you realize it, you can write quicksort as fast as bubble sort.

Algorithm

The divide-and-conquer strategy is used in quicksort. Below the recursion step is described:

  1. Choose a pivot value. We take the value of the middle element as pivot value, but it can be any value, which is in range of sorted values, even if it doesn’t present in the array.
  2. Partition. Rearrange elements in such a way, that all elements which are lesser than the pivot go to the left part of the array and all elements greater than the pivot, go to the right part of the array. Values equal to the pivot can stay in any part of the array. Notice, that array may be divided in non-equal parts.
  3. Sort both parts. Apply quicksort algorithm recursively to the left and the right parts.

Partition algorithm in detail

There are two indices i and j and at the very beginning of the partition algorithm i points to the first element in the array andj points to the last one. Then algorithm moves i forward, until an element with value greater or equal to the pivot is found. Index j is moved backward, until an element with value lesser or equal to the pivot is found. If i ≤ j then they are swapped and i steps to the next position (i + 1), j steps to the previous one (j – 1). Algorithm stops, when i becomes greater than j.

After partition, all values before i-th element are less or equal than the pivot and all values after j-th element are greater or equal to the pivot.

Example. Sort {1, 12, 5, 26, 7, 14, 3, 7, 2} using quicksort.

Quick Sort at Work


N
otice, that we show here only the first recursion step, in order not to make example too long. But, in fact, {1, 2, 5, 7, 3} and {14, 7, 26, 12} are sorted then recursively.

Why does it work?

On the partition step algorithm divides the array into two parts and every element a from the left part is less or equal than every element b from the right part. Also a and b satisfy a ≤ pivot ≤ b inequality. After completion of the recursion calls both of the parts become sorted and, taking into account arguments stated above, the whole array is sorted.

Complexity analysis

On the average quicksort has O(n log n) complexity, but strong proof of this fact is not trivial and not presented here. In worst case, quicksort runs O(n2) time, but on the most “practical” data it works just fine and outperforms other O(n log n) sorting algorithms.

Code snippets

Partition algorithm is important per se, therefore it may be carried out as a separate function. The code for C++ contains solid function for quicksort, but Java code contains two separate functions for partition and sort, accordingly.
JAVA

C/C++

Graphics in Turbo C/C++

Turbo C has a good collection of graphics libraries. If you know the basics of C, you can easily learn graphics programming. To start programming, let us write a small program that displays a circle on the screen.

    To run this program, you need graphics.h header file, graphics.lib library file and Graphics driver (BGI file) in the program folder. These files are part of Turbo C package. In all our programs we used 640×480 VGA monitor. So all the programs are according to that specification. You need to make necessary changes to your programs according to your screen resolution. For VGA monitor, graphics driver used is EGA.BGI or VGA.BGI.

Here, initgraph() function initializes the graphics mode and clears the screen. We will study the difference between text mode and graphics mode in detail latter.

InitGraph:
Initializes the graphics system.Declaration:
void far initgraph(int far *graphdriver, int far *graphmode, char far *pathtodriver);Remarks: To start the graphics system, you must first call initgraph.

initgraph initializes the graphics system by loading a graphics driver from disk (or validating a registered driver) then putting the system into graphics mode.

initgraph also resets all graphics settings (color, palette, current position, viewport, etc.) to their defaults, then resets graphresult to 0.
Arguments:

*graphdriver: Integer that specifies the graphics driver to be used. You can give graphdriver a value using a constant of the graphics drivers enumeration type.

*graphmode : Integer that specifies the initial graphics mode (unless *graphdriver = DETECT). If *graphdriver = DETECT, initgraph sets *graphmode to the highest resolution available for the detected driver. You can give *graphmode a value using a constant of the graphics_modes enumeration type.

pathtodriver : Specifies the directory path where initgraph looks for graphics drivers (*.BGI) first.  If they’re not there, initgraph looks in the current directory.  If pathtodriver is null, the driver files must be in the current directory.  This is also the path settextstyle searches for the stroked character font files (*.CHR).

closegraph() function switches back the screen from graphcs mode to text mode. It clears the screen also. A graphics program should have a closegraph function at the end of graphics. Otherwise DOS screen will not go to text mode after running the program. Here, closegraph() is called after getch() since screen should not clear until user hits a key.

If you have the BGI file in the same folder of your program, you can just leave it as “” only. you need not mention *graphmode if you give *graphdriver as DETECT.

In graphics mode, all the screen co-ordinates are mentioned in terms of pixels. Number of pixels in the screen decides resolution of the screen. In the example 1.0,  circle is drawn with x-coordinate of the center 200, y-coordinate 100 and radius 150 pixels. All the coordinates are mentioned with respect to top-left corner of the screen.

Basic Shapes and Colors:

Now let us write a program to draw some basic shapes.

 

Here is the screenshot of output:

Here, circle() function takes x, y coordinates of the circle with respect to left top of the screen and radius of the circle in terms of pixels as arguments. Note that, in graphics, almost all the screen parameters are measured in terms of pixels.

Function outtextxy() displays a string in graphical mode. You can use different fonts, text sizes, alignments, colors and directions of the text that we will study later. Parameters passed are x and y coordinates of the position on the screen where text is to be displayed. There is another function outtext() that displayes a text in the current position. Current position is the place where last drawing is ended. These functions are declared as follows:

void far outtextxy(int x, int y, char *text);
void far outtext(char *text);

Circle, arc, pieslice are declared as follows:

Declaration:

  •  void far arc(int x, int y, int stangle, int endangle, int radius);
  •  void far circle(int x, int y, int radius);
  •  void far pieslice(int x, int y, int stangle, int endangle, int radius);

Remarks:

  • arc draws a circular arc in the current drawing color.
  • circle draws a circle in the current drawing color.
  • pieslice draws a pie slice in the current drawing color, then fills it using
    the current fill pattern and fill color.

Arguments:

  • (x,y): Center point of arc, circlew, or pie slice
  • stangle: Start angle in degrees
  • endangle: End angle in degrees
  • radius: Radius of arc, circle, and pieslice

Here, stangle and endangle are in degrees starting from the +ve x-axis in the polar coordinate system in the anti-clockwise direction. if stangle is 0, endangle is 360, it will draw a full circle. Refer this figure for clear idea: For the details of current color, fill color and fill patterns, refer the sections Lines and Colors.

Another basic shape that we come across is a rectangle. To draw a border, use rectangle with the coordinates of outline, to draw a square use rectangle with same height and width. drawpoly() and fillpoly() are two functions useful to draw any polygons. To use these functions, store the coordinates of the shape in an array and pass the address of array as an argument to the function. By looking at the output of the previous program, you can understand what drawpoly is. fillpoly is similar except that it fills in the shape with current fill color.

Declaration:

  • void far rectangle(int left, int top, int right, int bottom);
  • void far drawpoly(int numpoints, int far *polypoints);
  • void far fillpoly(int numpoints, int far *polypoints);

Remarks:

  • rectangle draws a rectangle in the current line style, thickness, and drawing color.
  • drawpoly draws a polygon using the current line style and color.
  • fillpoly draws the outline of a polygon using the current line style and color, then fills the polygon using the current fill pattern and fill color.

Arguments: 

  • (left,top) is the upper left corner of the rectangle, and (right,bottom) is its lower right corner.
  •  numpoints:  Specifies number of points
  • *polypoints: Points to a sequence of (numpoints x 2) integers. Each pair of integers gives the x and y coordinates of a point on the polygon.

To draw a closed polygon with N points, numpoints should be N+1 and the array polypoints[] should contain 2(N+1) integers with first 2 integers equal to last 2 integers.

Let us study more about shapes latter. Here is some idea about colors. There are 16 colors declared in graphics.h as listed bellow.

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

To use these colors, use functions setcolor(), setbkcolor() and setfillstyle(). setcolor() function sets the current drawing color. If we use setcolor(RED); and draw any shape, line or text after that, the drawing will be in red color. You can either use color as defined above or number like setcolor(4);. setbkcolor() sets background color for drawing. Setfillstyle sets fill pattern and fill colors. After calling setfillstyle, if we use functions like floodfill, fillpoly, bar etc, shpes will be filled with fill color and pattern set using setfillstyle. These function declarations are as follows.

Declaration:

  •  void far setfillstyle(int pattern, int color);
  • void far setcolor(int color);
  • void far setbkcolor(int color);

Remarks:

  • setfillstyle sets the current fill pattern and fill color.
  • setcolor sets the current drawing color to color, which can range from 0 to getmaxcolor.
  • setbkcolor sets the background to the color specified by color.

The parameter pattern in setfillstyle is as follows:

 Names Value Means  Fill With…
EMPTY_FILL 0 Background color
SOLID_FILL 1 Solid fill
LINE_FILL 2
LTSLASH_FILL 3 ///
SLASH_FILL 4 ///, thick lines
BKSLASH_FILL 5 \\\, thick lines
LTBKSLASH_FILL 6  \\\
HATCH_FILL 7 Light hatch
XHATCH_FILL 8 Heavy crosshatch
INTERLEAVE_FILL 9 Interleaving lines
WIDE_DOT_FILL 10 Widely spaced dots
CLOSE_DOT_FILL 11 Closely spaced dots
USER_FILL 12 User-defined fill pattern

Here is an example program with colors, pixels, bar, cleardevice etc. stdlib.h is used for random number generation. We have a function random(no), it returns a random number between 0 an no. The effect is by drawing random radius, random color circles with same center and random pixels. kbhit() function(defined in conio.h) returns a nonzero value when a key is pressed in the keyboard. So, the loop will continue until a key is pressed.

Thank you for reading!

Finding the Right License Scheme for your Software

Software companies rely on license fees for their revenues. A number of different licensing schemes are available and each type has its advantages. The exact choice of licence scheme will depend on the target user and their way of deriving utility from the software. Below, you will find a detailed explanation of six types of license schemes. As a producer or consumer, knowledge of these different forms will assist you to choose what is right for your personal or organizational use.software licence

1. License by user
License by user infers that only one person has authorization to use the particular software. The user may use different devices but no other user is allowed to use the same software. If there are many employees in an organization, everyone has to get their own license. License per user works well with web-based software that does not tie a user to a particular physical location.

2. License by installation
This is different from the license by user because it does not restrict the number of users that can use the software. Instead, it restricts the usage of the software to only one device. If the software installation happens on a laptop or a tablet and the licensing also happens for that device, then any person who accesses the device will be able to use the software. Sellers prefer this license model when they expect very little mobility of the user and the software. The scheme works best for software bought for personal use.

3. License by client
When the software deployment takes place in a server environment where there are many server-clients, sellers may opt to licence by client. In this case, all devices that connect to the server to use the software will need a license. In addition, it is common for sellers to issue a license for the server that clients connect to, in the organization.

4. No license fees
Sometimes software can arise out of a voluntary effort and the creators may not have an inclination to earn from their work. In other cases, companies choose to not to sell their software license in the hope that, they will recoup their production costs when they provide paid support. Most open source software use a no license fees scheme.

5. Licence by developer
Just as some businesses only deal with other businesses, some software only works by assisting other software developers to create solutions for their customers. Development tools and libraries are critical software development components. The person using these tools may be compelled to acquire a developer license; however, the resulting software sold to end users will not be part of the license by developer.

6. License by site
Sometimes an organization has many employees with a high staff turnover. It does not make economic sense to buy every staff a user license. In addition, some employees might be working remotely and therefore need more than the license by installation, since they use more than one device. Such organizations and businesses can opt to acquire site licenses if the software seller offers them. The license by site allows anyone within the unit that qualifies as the site, to use the software. In most cases site can mean a physical local or an organization. For example, with organization as the site, the license may allow everyone who is an employee to access to the software irrespective of his or her location.

The exact limits of the rights of usage given by a specific license will always depend on the license scheme used. By following the description of each license scheme listed above you will be in a good position to select what will work best for your organization. The right license affords you the support that you need to keep your devices and organization secure. For sellers, choosing the right license scheme gives you the right options of marketing your software to clients.

Levenshtein Distance Algorithm with C++

Those with some courses or computer classes may understand better. For example,

  • If source string is “transform” and the target string is “transcend”, then the distance is 4 because the last four letters “form” will each be substituted respectively with “cend”.
  • If one string is “string” and other is “song”, then distance is 3 (I replacement, 2 deletions)
  • If one string is “gotcha” and other is also “gotcha”, this distance is zero because no transformations are needed. The strings are already identical.

The greater the Levenshtein distance, the more distinct the strings are.

Levenshtein distance is named on its inventor, the Russian scientist Vladimir Levenshtein, who devised the algorithm in 1965. The property is also called edit distance sometimes.

The Levenshtein distance algorithm is widely used for:

  • Spelling check
  • DNA analysis (surprised??)
  • Plagiarism detection (You may hate it or love it ;) )
  • Speech recognition

The Algorithm Steps

Step Description
1 Set n to be the source string with a length equal to s
Set m to be the target string with a length equal to t
If n = 0, return m.
If m = 0, return n.
Initialize a matrix with 0..m rows and 0..n columns.
2 Let the first row elements be equal to 0,1,…,n (in order)
Similarly assign the first column to 0,1,…,m
3 Loop through each character of s (i from 1 to n).
4 In a sub-loop, iterate each character of t (j from 1 to m).
5 If s[i] and t[j] are equal, the cost is 0.
If s[i] doesn’t equate to t[j], the cost is 1.
6 Assign to cell d[i,j] of the matrix to be equal to the minimum of:
a. The value of field immediately above, plus 1: d[i-1,j] + 1.
b. The value of field immediately to the left plus 1: d[i,j-1] + 1.
c. The value of field diagonally above and to the left plus the cost: d[i-1,j-1] + cost.
7 After the processing steps (3, 4, 5, 6) are complete, the distance is that stored in the cell d[n,m] in the end.

The Code for C++

Win32 Multithreading and Synchronization

Introduction:

This tutorial will explain how to create and manage multiple threads in Windows. This is an advanced tutorial; the reader should be familiar with Win32 programming.
The need for responsive user-centric programs is a good reason to create programs that use multiple threads. By creating multiple threads, a program can seem to do many things at once (on a computer with more than one CPU, the program actually will do many things at once). For example, a word processor could have one thread that handles the painting of the processor’s window while another thread saves the document being typed every few minutes while yet another thread actively monitors the document for spelling errors all without forcing the user to wait while each task is completed.

Background:

On a single CPU Windows machine, all threads are kept track of and given a slice of processor time (usually a few milliseconds). Windows will cycle through the list it keeps, pausing and resuming each thread. Once a thread has used up its time on the processor, Windows will pause the thread, record its CPU registers (along with some other data), and, after restoring all its data, activate the next thread. Each thread has two priorities: base and dynamic. The base priority can be changed, however, it cannot be changed to have a priority higher than that of the parent thread. Dynamic priority is the same as the base priority, however, it can be raised or lowered by Windows. Windows chooses which thread to run next based on the thread’s dynamic priority. Naturally, threads with a higher dynamic priority run first.

Multithreading:

Initially, every program gets one thread, known as the primary thread, which is created by the Windows Object Manager. The primary thread can be used to create child threads. To create another thread callCreateThread. CreateThread takes the following parameters:

If the first parameter is passed as NULL, the thread will get the default security descriptor. The second parameter allows you to set the initial stack size, you can pass 0 to give the thread the default stack size. The third parameter is a pointer to the function the thread should start executing. The fourth parameter holds any arguments you want to pass to the function. You can pass either a 0 or CREATE_SUSPENDED to the fifth parameter. If it is 0, the thread starts running as soon as it is created. If the value is CREATE_SUSPENDED, the thread will be created suspended and will not start running until you call ResumeThread. The last parameter is a pointer to a DWORD which will hold the unique ID of the thread, after it is created.

If a thread was created with the CREATE_SUSPENDED flag, you will want to call ResumeThread to start using it. ResumeThread takes the following parameter:

hThread is the handle received by CreateThread. To suspend the thread again, call SuspendThread:

Once again, hThread is the handle received by CreateThread.

While a thread is suspended, you may want to raise its base priority and then wake it again. A thread with a higher priority will get more processor time. To change a thread’s base priority, call SetThreadPriority:

nPriority can be one of seven values:

THREAD_PRIORITY_LOWEST Two levels below process
THREAD_PRIORITY_BELOW_NORMAL One level below process
THREAD_PRIORITY_NORMAL Normal priority
THREAD_PRIORITY_ABOVE_NORMAL One level above process
THREAD_PRIORITY_HIGHEST Two levels above process
THREAD_PRIORITY_TIME_CRITICAL Priority of 15
THREAD_PRIORITY_IDLE Priority of 1

To retrieve a thread’s base priority level, call GetThreadPriority:

After you are done using a thread, you may want to terminate it. To do this, call ExitThread. ExitThread followed by a CloseHandle is the graceful way to shut down a thread. To immediately stop a thread, callTerminateThread. The specs of each function are:

Windows automatically calls ExitThread when a thread ends its function. dwExitCode is the exit code you want to pass. The exit code can later be retrieved using GetExitCodeThread:

The following is an example of how to use threads.

Synchronization:

Picture this: a word processor program creates two threads, one to read a file and another to write to a file. Everything is fine at first, the first thread waits for the second to finish writing to the file before reading it. The two threads work happily, everything is fine as long as the writing thread always writes first. But one dark day, the reading thread reads the file before the writing thread writes to the file and the program fails. This is known as a race condition because both threads race to finish their file operation. The program will always fail if the reading thread wins the race. A race condition is the result of bad synchronization. Another problem is the dreaded deadlock. In a deadlock, both threads will wait for each other to finish but neither thread will finish until the other finishes first, causing them to become locked. The solution to this problem is to use one, or more, of the synchronization objects provided by Windows.

To gain ownership of any of the synchronization objects, a thread can use WaitForSingleObject, WaitForSingleObjectEx, WaitForMultipleObjects, or WaitForMultipleObjectsEx.

WaitForSingleObject allows a thread to suspend itself while it waits for ownership of one of the synchronization objects.

The second parameter is the amount of time, in milliseconds, the thread is willing to wait for the object before it returns. If the second parameter is set to INFINITE, the function will not time-out. If the second parameter is set to 0, the function will try to gain ownership of the object and return immediately, even if it didn’t gain ownership.

WaitForSingleObjectEx is the same as WaitForSingleObject except, it adds one more option: alert if I/O operation completes.

If the last parameter is set to true, the function will return when an asynchronous I/O operation completes.

WaitForMultipleObjects allows a thread to wait for multiple synchronization objects at once. It can be set to return when any or all of the objects become available.

If the third parameter is set to TRUE, the function will wait for all of the objects to become available. If the third parameter is set to FALSE, the function will wait for any of the objects to become available, the return value of the function will be the index to the handles array to let you know which object that has been obtained.

WaitForMultipleObjectsEx is the same as WaitForSingleObjectEx, except it allows you to wait for multiple objects.

Mutexes:

Like all other synchronization objects, a mutex is created by the Windows Object Manager. Mutex is short for mutual exclusion, meaning that only one thread can own it at a time. Think of it as a sort of ticket, any thread holding the ticket gets to access whatever is being protected by the mutex. While the thread is doing its job, all the other threads wait. Once the thread is done, it gives the ticket away and the next thread can do what it needs to do while the other threads wait.

To create a mutex call CreateMutex:

The first parameter can be passed as NULL to obtain the default access rights. If the second parameter is set to TRUE, the creator of the mutex will have ownership first. The third parameter is optional, it can be used to easily identify the mutex.

To release the mutex after doing whatever needs to be done, call ReleaseMutex.

Only the thread that owns the mutex can release it. To destroy the mutex, call CloseHandle with the handle to the mutex.

Semaphores:

A semaphore is useful when you want to only allow a limited amount of threads to access a protected resource at a time. With a mutex, only one thread can own it at any given moment. With a semaphore, multiple threads can own it at a time. Consequently, any thread can also destroy the semaphore. To create a semaphore call CreateSemaphore.

The first parameter is handled the exact same as the first parameter of CreateMutex. The second parameter sets the initial count of the semaphore, usually it’s set to the same value as that of the maximum count. The initial count cannot be less than zero nor greater than the maximum count. The third parameter sets the maximum count which limits the number of threads that can own the semaphore. The last parameter is handled the same way as that of CreateMutex. After a thread gains possession of the semaphore the initial count is decremented one. If the initial count reaches 0, no more threads can gain possession of the semaphore. The initial count is incremented after a thread releases the semaphore.

To release a semaphore, call ReleaseSemaphore.

The second parameter sets by how much the count should be incremented, usually this is 1. The third parameter holds a pointer to a variable that will be filled with the previous count, after ReleaseSemaphore completes.

Critical Sections:

A critical section is very similar to a mutex. A critical section can only be owned by one thread at a time, however, a critical section cannot be shared between processes, a mutex can. Because of this, a critical section works more quickly. To create a critical section, call InitializeCriticalSection; to own a critical section, call EnterCriticalSection; to give up ownership of a critical section, call LeaveCriticalSection; to destroy a critical section, call DeleteCriticalSection.

All of the functions require a pointer to the critical section object. You declare one like this:

Any thread that is of the process that created the critical section can destroy the critical section.

Events:

An event object is useful when you want to alert threads of an action occurring, a button being pushed for example. An event object is sent to all waiting threads. Call CreateEvent to create an event; call SetEvent to signal an event; call ResetEvent to turn the signal off. When an event is signaled, all threads that wait for it will receive it; when the event is not signaled, the threads will wait. You can also call PulseEvent to quickly signal and unsignal an event. This is useful in releasing the waiting threads.

CreateEvent takes the following parameters:

If the second parameter is set to TRUE, the event must be reset manually. If the second parameter is set to FALSE, the event will return to its unsignaled state immediately after a call to SetEvent. If the third parameter is set to TRUE, the event will be created and set to the signaled state. The last parameter is an optional name for the object.

SetEvent, ResetEvent, and PulseEvent are all called in the same way:

hEvent being the handle returned from CreateEvent.

The combination of a mutex and an event is a good way to avoid deadlocks. The following is an example of using the mutex and event synchronization objects.

Mouse Programming in Turbo C++

Mouse can be used in text mode as well as in graphics mode. Usually it is used in graphics mode. Hence we must first change over to graphics mode. In our program the function initgraph() is responsible for switching the mode from text to graphics. DETECT is a macro defined in ‘graphics.h’. It requests initgraph() to automatically determine which graphics driver to load in order to switch to the highest resolution graphics mode. The initgraph() function takes three parameters, the graphics driver, the graphics mode and the path to the driver file.

Once the driver has been loaded, initgraph() sets up the numeric values of the graphics mode chosen in the variables gd and gm respectively. Here we are assuming that the driver files are in the directory ‘c:\tc\bgi’. Hence the path passed to initgraph() is ‘c:\tc\bgi’

The various mouse functions can be accessed by setting up the AX register with different values (service number) and issuing interrupt number 51. The functions are listed bellow.

Interrupt Service Purpose
51 0

 Reset mouse and get status
Call with AX = 0
Returns:  AX = FFFFh If mouse support is available
Ax = 0 If mouse support is not available

51 1

 Show mouse pointer
Call with AX = 1
Returns: Nothing

51 2

 Hide mouse pointer
Call with AX = 2
Returns: Nothing

51 3

 Get mouse position and button status
Call with AX = 3
Returns: BX = mouse button status
Bit   Significance
0     button not pressed
1     left button is pressed
2     right button is pressed
3     center button is pressed
CX = x coordinate
DX = y coordinate

51 4

 Set mouse pointer position
Call with AX = 4
CX = x coordinate
DX = y coordinate
Returns: Nothing

51 7

 Set horizontal limits for pointer
Call with AX = 7
CX = minimum x coordinate
DX = maximum x coordinate
Returns: Nothing

51 8

 Set vertical limits for pointer
Call with AX = 8
CX = minimum y coordinate
DX = maximum y coordinate
Returns: Nothing

 Let us consider a program which makes use of the above functions.

  The above program makes use of the following functions:

  • callmouse();
  • mouseposi();
  • mousehide(); 
  • setposi();

callmouse()
In this function AX is set to “1″. When this function is called in main() it displays the mouse pointer. The position of the pointer can be changed by using the mouse.

mousehide()
In this function AX is set to “2″.When this function is called in main() it hides the mouse pointer. This function is useful while drawing  figures, first the mouse pointer is kept hidden, then the figure is been drawn and again the mouse pointer is been called.

mouseposi()
In this function AX is set to “3″. This function returns the position of the mouse pointer. It contains three parameters,they are xpos,ypos,click. xpos and ypos returns the position of x co-ordinate and y co-ordinate respectively. Click is the integer variable which returns the values 1,2,3 corresponding to the button pressed on the mouse and 0 for buttons being not pressed. If any key is pressed kbhit returns nonzero integer; if not it returns zero.

setposi()
In this function AX is set to “4″. This function sets the mouse pointer to specific position . CX is been loaded by x co-ordinate of the mouse pointer and DX is been loaded with the y co-ordinate of the mouse pointer.

    Let us consider another program

The above program makes use of the following functions:

  • Horizontal();
  • Vertical(); 

 

Horizontal()
In this function AX is set to “7″. Its sets the horizontal barrier for the pointer which restricts the mouse pointer to pass that limit. CX is been loaded with the minimum x co-ordinate and Dx is been loaded with the maximum x co-ordinate.

Vertical()
In this function AX is set to “8″.Its sets the vertical barrier for the pointer which restricts the mouse pointer to pass that limit. CX is been loaded with the minimum y co-ordinate and Dx is been loaded with the maximum y co-ordinate.