Level - Beginner

In this tutorial you will learn how to do mouse programming through C. Mouse Programming in C is simple and beginners can give it a shot if they undestand carry on otherwise read the basic tutorials first and then comeback and learn how to do Mouse Programming using C. Before we get our hands dirty we begin with a breif intro.

Mouse has revolutionized the Computer World . It was introduced with GUI which stands for Graphical User Interface.

It was a big step forward thrusting computer from command line execution to hot and happening menu driven applications that we see today. Many GUI were based on keyboards but they never outweighed thier opponents based on mouse reason is simple, just imagine your Windows or Linux to be keyboard driven. Nothing less than a nightmare it seems.

Mouse is simple input device which allows you to point and execute interface and is faster than keyboards many times. Mouse generally provide random interface on other hand keyboards provide sequential interface.

This article will act as a complete source of Mouse Programming in C and covers it all aspects. If we still miss something please inform us and we will try to cover it next revised edition.

Mouse Programming is a topic which every c programmer from begginer to professional needs to have in his toolbox to have a cutting edge.

Mouse Programming will be used almost everywhere. It will embeded in games programming to commerical valued applications. So if you aim to easily understand other tutorials in this website you must master this topics and believe me its very easy.

Contents -

1. Requirements
2. Fundamental Knowledge.
3. AX Register
4. Detecting Mouse
5. S
howing & Hiding Mouse
6. Detecting Input
7. Mouse Coordinates
8. Restricting Mouse
9. What Next?

1. Requirements

First and Formeost requirement which i believe will surely be satisfyied, you should have a mouse attached to your system.

This tutorial is written Turbo C++ 3.0 IDE and install in folder C:\TC. I recommend to use same IDE and settings to avoid any uncompatibility and even if you face any problem we provide an 24 X 7 Email Support to help you out.

You should have proper mouse driver for your hardware, this is also not a problem because almost 100% of operating System provide them through program MOUSE.COM or WITTYMS.COM.

That is all you need.


2. Fundamental Knowledge

Before we start harcore programming we must first understand some principles on which mouse programming is based.

First thing you must know how to tell a mouse to do anything. In actual we doesnot communicate with mouse directly but through the driver provide. We use interrupts to get access to this driver. Each device provide by computer has its own port and more or less we access these ports.

Each device has a unique port which is a hexadecimal value and value is designed to be machine independent enhancing portability of program.

Mouse has port attached to it 0X33 and similarly keyboard has attach to it port 0X60. We restrict ourself only to mouse port in this tutorial but keyboard is also used extensively in other programs especially ones related to games programming.

We also make use of address registers. These are basically Union of type REGS defined in dos.h. You dont need further knowledge of them for programming. Just remember we use two register to communicate to a device driver using two registers one for input and one for output.

We send value to device driver through the input register and recieve information in it embedded in output register.


3. AX Register

We can access various mouse functions using different values of AX input Register and passing those values to mouse port using a interrupt

The Functions are listed below - Here AX, BX, CX and DX are members of Union REGS and more or less integers.

Input                   Function Performed             Returns


AX = 0 Get Mouse Status Output AX Value = FFFFh if mouse support is available.
Output AX Value = 0 if mouse support is not available.


AX = 1 Show Mouse Pointer Nothing


AX = 2 Hide Mouse Pointer Nothing


AX = 3 Mouse Position CX = Mouse X Coordinate
DX = Mouse Y Coordinate


Ax = 3 Mouse Button Press BX = 0 No Key Is Pressed

BX = 1 Left Button is Pressed
BX = 2 Right Button is Pressed

BX = 3 Centre Button is Pressed


Ax = 7 Set Horizontal Limit Nothing
CX = MaxX1
DX =MaxX2


Ax = 8 Set Vertical Limit Nothing
CX = MaxX1
DX =MaxX2


Now we step by step study each of these services in following sections and build up our combined code.

4. Detect Mouse

Before you start your embed mouse program you should always check wether the mouse programming is supported on not.

If some how mouse fails to initalise you should always make sure that either program terminates or employ a error handling approach that maybe shift to keyboard interface .

To do mouse programming you must include . We use a function called int86 to access interupts.

To detect mouse we use a function name detectmouse which has following code -

#include 
union REGS in, out;
void detectmouse ()
{
in.x.ax = 0;
int86 (0X33,&in,&out);
if (out.x.ax == 0)
printf ("\nMouse Fail To Initialize");
else
printf ("\nMouse Succesfully Initialize");
}
int main ()
{
detectmouse ();
getch ();
return 0;
}

5. Showing and Hiding Mouse

Now first we show mouse on screen .

Mouse works both in text mode and graphic mode.

In text mode it looks like a square while in graphics mode it looks like a pointer.

Here is a screen shot for text mode.

Mouse Programming in Text Mode

It was produced from adding a function showmousetext to above code so code becomes -



Here is a screen shot for graphic mode -


Mouse Programming in Graphics Mode


This is achieved using a function showmousegraphic added to above code while removing showmouse text from main.

#include 
#include
union REGS in, out;
void detectmouse ()
{
in.x.ax = 0;
int86 (0X33,&in,&out);
if (out.x.ax == 0)
printf ("\nMouse Fail To Initialize");
else
printf ("\nMouse Succesfully Initialize");
}
void showmousetext ()
{
in.x.ax = 1;
int86 (0X33,&in,&out);
}
void showmousegraphics ()
{
int gdriver = DETECT, gmode, errorcode;
initgraph(&gdriver, &gmode, "c:\\tc\\bgi");
in.x.ax = 1;
int86 (0X33,&in,&out);
getch ();
closegraph ();
}
int main ()
{
detectmouse ();
showmousegraphics ();
getch ();
return 0;
}

Next we do realtively simple task of hiding mouse using a function hidemouse as shown below -
#include 
#include
union REGS in, out;
void detectmouse ()
{
in.x.ax = 0;
int86 (0X33,&in,&out);
if (out.x.ax == 0)
printf ("\nMouse Fail To Initialize");
else
printf ("\nMouse Succesfully Initialize");
}
void showmousetext ()


{
in.x.ax = 1;
int86 (0X33,&in,&out);
}
void showmousegraphics ()


{
int gdriver = DETECT, gmode, errorcode;
initgraph(&gdriver, &gmode, "c:\\tc\\bgi");
in.x.ax = 1;
int86 (0X33,&in,&out);
getch ();
closegraph ();
}
void hidemouse ()
{
in.x.ax = 2;
int86 (0X33,&in,&out);
}
int main ()
{
detectmouse ();
showmousegraphics ();
hidemouse ();
getch ();
return 0;
}

6. Detect Input

We will now work on a important aspect of mouse programming detecting clicks.

We make use of an aditional function known as kbhit ( ). This functions returns zero till any keypress and when a key is press it returns 1.

We use kbhit to run a infinite while loop.

For detecting mouseclicks we use a function called detect which displays on screen the respective button clicked. Press any keyboad key to exit the loop.

#include 
#include
union REGS in, out;
void detectmouse ()


{
in.x.ax = 0;
int86 (0X33,&in,&out);
if (out.x.ax == 0)
printf ("\nMouse Fail To Initialize");
else
printf ("\nMouse Succesfully Initialize");
}
void showmousetext ()


{
in.x.ax = 1;
int86 (0X33,&in,&out);
}
void showmousegraphics ()


{
int gdriver = DETECT, gmode, errorcode;
initgraph(&gdriver, &gmode, "c:\\tc\\bgi");
in.x.ax = 1;
int86 (0X33,&in,&out);
getch ();
closegraph ();
}
void hidemouse ()


{
in.x.ax = 2;
int86 (0X33,&in,&out);
}
void detect ()


{
while (!kbhit () )
{
in.x.ax = 3;
int86 (0X33,&in,&out);
if (out.x.bx == 1) printf ("Left");
if (out.x.bx == 2) printf ("Right");
if (out.x.bx == 3) printf ("Middle");
delay (100); // Otherwise due to quick computer response 100s of words will get print
}
}

int main ()
{
detectmouse ();
showmousetext ();
detect ();
hidemouse ();
getch ();
return 0;
}

7. Mouse Coordinates

We can obtain the coordinates of the mouse using same service 3 but using different elments of the union .

This function has a prime use in games programming, application designing and GUI development. Different decisions are taken on same left button click, its the postion of click that matters.

BX element of output registers stores the X Coordinate of the postion of mouse at time of calling function.

CX element of output registers stores the Y Coordinate of the postion of mouse at time of calling function.

Now we demonstrate the use of this function by modifying detect function above to display x,y and y coordinates on screen when left click is pressed.

Code will be as followed -

#include 
#include
union REGS in, out;
void detectmouse ()
{
in.x.ax = 0;
int86 (0X33,&in,&out);
if (out.x.ax == 0)
printf ("\nMouse Fail To Initialize");
else
printf ("\nMouse Succesfully Initialize");
}
void showmousetext ()
{
in.x.ax = 1;
int86 (0X33,&in,&out);
}
void showmousegraphics ()
{
int gdriver = DETECT, gmode, errorcode;
initgraph(&gdriver, &gmode, "c:\\tc\\bgi");
in.x.ax = 1;
int86 (0X33,&in,&out);
getch ();
closegraph ();
}
void hidemouse ()
{
in.x.ax = 2;
int86 (0X33,&in,&out);
}
void detect ()
{
while (!kbhit () )
{
int x,y;
in.x.ax = 3;
int86 (0X33,&in,&out);
if (out.x.bx == 1)
{
x = out.x.cx;
y = out.x.dx;
printf ("\nLeft || X - %d Y - %d", x, y);
}
if (out.x.bx == 2) printf ("\nRight");
if (out.x.bx == 3) printf ("\nMiddle");
delay (10); // Otherwise due to quick computer response 100s of words will get print
}
}
int main ()
{
detectmouse ();
showmousetext ();
detect ();
hidemouse ();
getch ();
return 0;
}


8. Restricting Mouse

We now restrict the mouse in particular rectangle .

We create a function called restrict which takes four paramters, two cartesian points each containing one x coordinate and one y coordinate.

First point mentions the top of the rectangle while second point mention the bottom bottom point of rectangle.

This service has limited uses but can be quite handy in special circumstances, for eg - if you want to restrict your mouse in one particular size window in GUI or In Games Programming.

Now i give you final code of the tutorial -

#include 
#include
union REGS in, out;
void restrict (int x1,int y1,int x2, int y2)
{
in.x.ax = 7;
in.x.cx = x1;
in.x.dx = x2;
int86 (0X33,&in,&out);
in.x.ax = 8;
in.x.cx = y1;
in.x.dx = y2;
int86 (0X33,&in,&out);
}
void detectmouse ()


{
in.x.ax = 0;
int86 (0X33,&in,&out);
if (out.x.ax == 0)
printf ("\nMouse Fail To Initialize");
else
printf ("\nMouse Succesfully Initialize");
}
void showmousetext ()


{
in.x.ax = 1;
int86 (0X33,&in,&out);
}
void showmousegraphics ()


{
int gdriver = DETECT, gmode, errorcode;
initgraph(&gdriver, &gmode, "c:\\tc\\bgi");
in.x.ax = 1;
int86 (0X33,&in,&out);
getch ();
closegraph ();
}
void hidemouse ()
{
in.x.ax = 2;
int86 (0X33,&in,&out);
}
void detect ()


{
while (!kbhit () )
{
int x,y;
in.x.ax = 3;
int86 (0X33,&in,&out);
if (out.x.bx == 1)
{
x = out.x.cx;
y = out.x.dx;
printf ("\nLeft || X - %d Y - %d", x, y);
}
if (out.x.bx == 2) printf ("\nRight");
if (out.x.bx == 3) printf ("\nMiddle");
delay (10); // Otherwise due to quick computer response 100s of words will get print
}
}
int main ()
{
detectmouse ();
showmousetext ();
restrict (100,100,500,500); // Change values here to create different mouse movement space.
detect ();
hidemouse ();
getch ();
return 0;
}


9. What Next ?

Now first thing you must do is congratulate yourself because you just added a super weapon to you arsenal.

Now there is no stopping you. Let your creativity flow and world class products come out of your computer.

To get you started here what you can do with mouse programming -

1. Games Programming

2. Commercial Applications Development.

3. Graphical User Interface

4. Utitlity Softwares such as Paint, Word Processors , Spread Sheets and so on....

Before you get your hands dirty we recommend you go through our game building and application building Tutorials. Most of them are based mouse programming.

Also if you still want to hone your mouse programming skills further go through our advance tutorials such as mouse cursors, mouse drawing, menu through mouse and more...

Stacks

Well, its a list with a difference! When I call it a List, it has to hold data of same type only; meaning, you can have a stack of either books or coins or anything which can be possibly stacked but you can't have a stack having books and coins both in it. You know what will happen! The stack will get imbalanced and its elements will fall down but that's not the desirable situation.

We are talking about the most idle case when we are dealing with computers, in which you can add an element from the TOP and take off and element from the TOP only. You can keep on adding elements to the stack till the time the stack is not imbalanced (i.e starts overflowing) and you can remove elements from the stack till the time its not empty.

In a list, you can add or delete elements at any position, but in a Stack you'll have to follow the LIFO (Last In First Out) principle. The last element added to the Stack can be the only one to be deleted first. Follow the example -

I have the following elements with me - 14, 23, 1, 4, 45(all integers) and I have a Stack with the upper limit set to 5. So, as you can see, I can accommodate all my elements in that stack.

Initially, the STACK is empty and the TOP of the STACK is pointing to the BOTTOM of the STACK.
Stage [A]: We added 14 and TOP now points to it.
Stage [B]: 23 is PUSHed and TOP is incremented by 1.
Stage [C]: The STACK is FULL, as the upper limit was set to 5.
Stage [D]: The TOPmost element has been POPed. The TOP gets decremented by 1.
Stage [E]: 45, 4, 1 and 23 have been POPed and TOP is now pointing to the bottom most element.

Every time you Push() an element inside the Stack, the TOP of the Stack gets incremented by 1 and vice-versa. When the STACK is empty, the BOTTOM and TOP of the STACK are same and pointing to the empty STACK. If you try to PUSH more elements than the upper limit of the STACK, it will cause in an overflow of data and vice-versa.

OK, why do we need such a data structure? Well, Stacks help computer in unfolding the recursive jobs; used in converting an expression to its postfix form; used in Graphs to find their traversals (we have seen that); helps in non-recursive traversal of binary trees (we'll see this) and so on....

Haven't you realised that the regular, static queues we saw have a very big drawback that once the queue is FULL, even though we delete few elements from the "front" and relieve some occupied space, we are not able to add anymore elements, as the "rear" has already reached the Queue's rear most position. The solution lies in a queue in which the moment "rear" reaches the Queue's watermark, the "first" element will become the queue's new "rear".

As the name suggests, this Queue is not straight but circular; meaning, you got to have a structure like this -
in which, once the Queue is full the "First" element of the Queue becomes the "Rear" most element, if and only if the "Front" has moved forward; otherwise it will again be a "Queue overflow" state.....Hope! the sky hasn't fallen as yet.

Here, as you can see, the "front" value is 0 and the "rear" value is 5.

Initially, when such a queue is empty, the "front" and the "rear" values are 0 & -1 respectively; and the queue has a NULL value for all its element. Every time we add an element to the queue, the "rear" value increments by 1 till the time it reaches the upper limit of queue; after which it starts all over again from 0. Similarly, every time we delete an element from queue, the "front" value increments by 1 till the time it reaches the upper limit of queue; after which it starts all over again from 0.

Algorithm for Insertion:-
Step-1: If "rear" of the queue is pointing to the last position then go to step-2 or else step-3
Step-2: make the "rear" value as 0
Step-3: increment the "rear" value by one
Step-4: a. if the "front" points where "rear" is pointing and the queue holds a not NULL value
for it, then its a "queue overflow" state, so quit; else go to step-b
b. insert the new value for the queue position pointed by the "rear"

C implementation:-
int max; /*the maximum limit has already been set*/
static int queue[max];
int front=0, rear=-1; /*queue is initially empty*/
..
..
main( )
{
..
..
addval(23);
..
addval(45);
..
addval(47);
..
}

addval( int new)
{
if(rear == max-1) /*step-1*/
rear = 0; /*step-2*/
else
rear = rear + 1; /*step-3*/
if( front == rear && queue[front] != NULL) /*step-4*/
printf("Queue Overflow"); /*step-a*/
else
queue[rear] = new; /*step-b*/
}

Note:- I have implemented this topic using arrays only as Circular queues are used only when limited memory space is there and static implementation is required, so that one can optimally utilize the allocated memory space.

Queues

Haven't you heard about a bus queue! There the people stand and here a computer element has to stand waiting for its turn to be processed. As you know, in a real life queue the one who gets in first, comes out first. Here also, the element which gets in the Queue first comes out first; and that's why we call it a FIFO structure( First-in-first-out). Logically, it looks like this

The new element will add itself from the 'rear' end and will come out from the 'front' end. When you add an element the Queue's 'rear' value increments by one and when an element leaves the queue the Queue's 'front' value increments by one, how! Deletion is there, the front should get decremented!

Well, its not the case because, as you know, when the first person leaves the queue, its the second person who becomes the Queue's new front. That's why -- each time an element leaves the queue the 'front' gets incremented by one.

Referring the above figure, you can make out that 26 was the first one to add itself to the queue then 09,...., and finally 24 is the last one to add itself. As you know, 26 will be the first one to come out, then 09,....and finally 24 will be the last one to come out.

When 'front' value becomes greater than the 'rear' value, we say -- the Queue is empty.

The queue has one of the best roles to play in computer's resource management like -- it is used in scheduling the jobs to be processed by the processor; a queue schedules the order of the print files to be printed; a server maintains a queue of the client requests to be processed and many more.

In this section you will know power of structure and union.


In the header file there are two important structures and union (Remember this structure)
1. struct BYTEREGS {
unsigned char al, ah, bl, bh;
unsigned char cl, ch, dl, dh;
};

2.struct WORDREGS {
unsigned int ax, bx, cx, dx;
unsigned int si, di, cflag, flags;
};

3.union REGS {
struct WORDREGS x;
struct BYTEREGS h;
};
In there is function int86().It general 8086 software interrupt interface. It will better to explain it by an example.

Write a c program to display mouse.
Ans:

#include
#include
void main()
{
union REGS i,o;
i.x.ax=1;
int86(0x33,&i,&o);
getch();
}
Explanation: To write such program interrupt table is necessary.




To see complete interrupt table click here
It is a small part of interrupt table. It has four field input,output,service number and purpose ,
Now see the first line which is inside the rectangle. To display the mouse pointer assign ax equal to 1 i.e service number while ax is define in the WORDREGS

struct WORDREGS {
unsigned int ax, bx, cx, dx;
unsigned int si, di, cflag, flags;
};

and WORDRGS is define in the union REGS


union REGS {
struct WORDREGS x;
struct BYTEREGS h;
};
So to access the ax first declare a variable of REGS i.e

REGS i,o;
To access the ax write i.x.ax (We are using structure variable i because ax is input,see interrupt table)
So to display mouse pointer assign the value of service number:
i.x.ax=1;
To give the this information to microprocessor
We use int86 function.It has three parametr
1. interrupt number i.e 0x33
2. union REGS *inputregiste i.e &i
3. union REGS *outputregiste i.e &o;
So write : int86(0x33,&i,&o);
(Compelete interrpt table with interrupt number and purpose is aviable at next post

search in content )

(q)Write a c program which restrict the movement of pointer?
Ans:
//restric the x and y cordinate
#include
#include
void main()
{
union REGS i,o;
//show mouse pointer
i.x.ax=1;
int86(0x33,&i,&o);
//x cordinate restiction
i.x.ax=7;
i.x.cx=20;
i.x.dx=300;
int86(0x33,&i,&o);
//y cordinate restriction
i.x.ax=8;
i.x.cx=50;
i.x.dx=250;
int86(0x33,&i,&o);
getch();
}





PASSING ONE-DIMENSIONAL ARRAY TO A FUNCTION





















































Question C

Followers

 
C - Programming -