Skip to content

C Tutorial #5:- Working with mouse

March 25, 2012

Before working with the mouse, first, download the  Mouse.h

header file.

Click here to download

After download paste the mouse.h file in your TC Folder.

Let us write a program for sample mouse functioning program where, when a user click on  a button, a  text will displayed welcoming the user.

#include<mouse.h>
#include<graphics.h>
#include<conio.h>
main()
{
int gd,gm;
int button,x,y;
detectgraph(&gd,&gm);

initgraph(&gd,&gm,” “);

initmouse();

showmouseptr();

rectangle(20,20,60,60);
while(!kbhit())
{
getmousepos(&button,&x,&y);

if ( (button&1) == 1  && (x >20 && x <60) && (y>20 && y<60) )
{
outtextxy(200,200,”Welcome”);
}
}

getch();
}

Let us understand the program.

1. With using initgraph(), we initialized the Graphics mode in our C Program.

2. next, with the use of initmouse(), we initialized the mouse pointer. It is a function defined in “mouse.h”

3. next, with the use of showmouseptr(), we are displaying mouse pointer.

4. next, we have drawn a rectangle.

5. we have put up a while loop..and condition is

! kbhit() :- note that there is logical NOT operator before that.

kbhit will return “0” (ZERO) when there is NO KEY is pressed in the keyboard.

will return “1” (One) when any key is pressed.

So, While loop will run until when no key is pressed.

6. Next, getmousepos(&button,&x,&y); here , we are passing addresses of three integer variables.

getmousepos() full place the button status and x,y mouse present coordinates into button,x, and y..variables.

what is the button status.

Button is an integer variable i.e 2 bytes or 16 bits.

If left button is clicked,then First Bit of Button is set as 1.

If Right button is clicked, then second bit is enabled.

So, in order to check which bit is enabled,

we use bitwise operators.

if AND operation is done between BUTTON status  and 00001, we get result as 1 if  left click is done.

if we do operation between  BUTTON status and 000002, we get result as 2.

again, we have to define the Rectangle coordinates in if condition.

Advertisements

From → C Graphics, Tutorials

2 Comments
  1. sairam permalink

    bro can u say the syntax of “outtextxy” function and its use …?

  2. @Sairam The outtextxy is similar to printf() in graphics mode.The Syntax of outtextxy is outtextxy(x,y,”example”) where x,y are starting letter coordinates of the string. Here, the string is “example”. so, the coordinates of ‘e’ (starting letter of example) have to be specified.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: