You are here

C program to get current position of mouse pointer

This program prints the x and y coordinates of current position of mouse pointer i.e. wherever you move the mouse coordinates of that point will be printed on the screen.
/* Program to get mouse-pointer coordinates - where is the mouse */

C programming code

  1. #include<graphics.h>
  2. #include<conio.h>
  3. #include<stdio.h>
  4. #include<dos.h>
  5.  
  6. int initmouse();
  7. void showmouseptr();
  8. void hidemouseptr();
  9. void getmousepos(int*,int*,int*);
  10.  
  11. union REGS i, o;
  12.  
  13. main()
  14. {
  15.    int gd = DETECT, gm, status, button, x, y, tempx, tempy;
  16.    char array[50];
  17.  
  18.    initgraph(&gd,&gm,"C:\\TC\\BGI");
  19.    settextstyle(DEFAULT_FONT,0,2);
  20.  
  21.    status = initmouse();
  22.  
  23.    if ( status == 0 )
  24.       printf("Mouse support not available.\n");
  25.    else
  26.    {
  27.       showmouseptr();
  28.  
  29.       getmousepos(&button,&x,&y);
  30.  
  31.       tempx = x;
  32.       tempy = y;
  33.  
  34.       while(!kbhit())
  35.       {
  36.          getmousepos(&button,&x,&y);
  37.  
  38.          if( x == tempx && y == tempy )
  39.          {}
  40.          else
  41.          {
  42.             cleardevice();
  43.             sprintf(array,"X = %d, Y = %d",x,y);
  44.             outtext(array);
  45.             tempx = x;
  46.             tempy = y;
  47.          }
  48.       }
  49.    }
  50.  
  51.    getch();
  52.    return 0;
  53. }
  54.  
  55. int initmouse()
  56. {
  57.    i.x.ax = 0;
  58.    int86(0X33, &i, &o);
  59.    return ( o.x.ax );
  60. }
  61.  
  62. void showmouseptr()
  63. {
  64.    i.x.ax = 1;
  65.    int86(0X33, &i, &o);
  66. }
  67.  
  68. void getmousepos(int *button, int *x, int *y)
  69. {
  70.    i.x.ax = 3;
  71.    int86(0X33, &i, &o);
  72.  
  73.    *button = o.x.bx;
  74.    *x = o.x.cx;
  75.    *y = o.x.dx;
  76. }