You are here

C program to restrict mouse pointer in a circle

C program to restrict mouse pointer in a circle, i.e, you can't move it out of the circle. When you try to bring it outside of the circle, it is moved to it's previous location which was inside the circle.

C programming code

  1. #include<graphics.h>
  2. #include<conio.h>
  3. #include<dos.h>
  4. #include<stdlib.h>
  5. #include<math.h>
  6.  
  7. union REGS i, o;
  8.  
  9. int initmouse()
  10. {
  11.    i.x.ax = 0;
  12.    int86(0X33, &i, &o);
  13.    return ( o.x.ax );
  14. }
  15.  
  16. void showmouseptr()
  17. {
  18.    i.x.ax = 1;
  19.    int86(0X33, &i, &o);
  20. }
  21.  
  22. void hidemopuseptr()
  23. {
  24.    i.x.ax = 2;
  25.    int86(0X33, &i, &o);
  26. }
  27.  
  28. void getmousepos(int *x, int *y)
  29. {
  30.    i.x.ax = 3;
  31.    int86(0X33, &i, &o);
  32.    *x = o.x.cx;
  33.    *y = o.x.dx;
  34.  
  35. }
  36.  
  37. void movemouseptr(int x, int y)
  38. {
  39.    i.x.ax = 4;
  40.    i.x.cx = x;
  41.    i.x.dx = y;
  42.    int86(0X33, &i, &o);
  43. }
  44.  
  45. main()
  46. {
  47.    int gd = DETECT, gm, midx, midy, radius, x, y, tempx, tempy;
  48.  
  49.    radius = 100;
  50.  
  51.    initgraph(&gd, &gm, "C:\\TC\\BGI");
  52.  
  53.    if(!initmouse())
  54.    {
  55.       closegraph();
  56.       exit(1);
  57.    }
  58.  
  59.    midx = getmaxx()/2;
  60.    midy = getmaxy()/2;
  61.  
  62.    showmouseptr();
  63.    movemouseptr(midx, midy);
  64.    circle(midx, midy, radius);
  65.  
  66.    x = tempx = midx;
  67.    y = tempy = midy;
  68.  
  69.    while(!kbhit())
  70.    {
  71.       getmousepos(&x, &y);
  72.  
  73.       if((pow(x-midx,2)+pow(y-midy,2)-pow(radius,2))>0)
  74.       {
  75.          movemouseptr(tempx, tempy);
  76.          x = tempx;
  77.          y = tempy;
  78.       }
  79.  
  80.       tempx = x;
  81.       tempy = y;
  82.    }
  83.  
  84.    closegraph();
  85.    return 0;
  86. }