TweetFollow Us on Twitter

Cursor Control 2
Volume Number:6
Issue Number:9
Column Tag:C Workshop

Related Info: Quickdraw

Cursor Control

By Robert S. T. Gibson, Ontario, Canada

Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.

[Robert S. T. Gibson is a Senior Software Engineer at Atryx Software Design in Canada]

Although it is not suggested by anyone who follows the Macintosh user interface, it is occasionally necessary for a program to change or restrict the cursor position. Some programs move the cursor to lock it into a grid, some restrict the cursor to a specific region, and others (usually games) allow it to wrap around the screen. Games sometimes read the cursor position, compare it to the middle of the screen, and then move the cursor to the screen’s center to keep it from reaching the edge.

Cursor tracking is maintained by many system globals. The three we are interested in, however, are MTemp, RawMouse, Mouse, and CrsrNew (see Figure 1).

It is often dangerous to change the System’s low-memory globals if you don’t know their exact effects on your system.

As always, there is a right way and a wrong way to do this. I’ll skip the wrong way and get right to what I believe to be the correct way. The C techniques used here can easily be adapted into other programming languages.

It is a relatively simple task to set the mouse position, but it requires a bit of insight into how the System keeps control.

Figure 1. Mouse Globals

System Control

Operation of the mouse depends on two routines that are called during interrupts. The first routine simply sets the global variable CrsrNew to true if the mouse position has changed. The second routine is a vertical retrace (VBL) task, which checks the value of CrsrNew and draws the cursor in the new position if the value is true.

Providing CrsrNew is set, each time the VBL task is executed, it draws the cursor and copies the value of MTemp, the new location of the mouse, into the variable RawMouse, the saved (old) location. This allows the next execution to examine the two variables. If MTemp is a valid position, RawMouse is set to the new position and the cycle continues. The mouse location is copied in to the global variable Mouse for use by routines such as GetMouse().

Program Control

Only a few simple steps are required to set the mouse position properly and safely:

Step:

1: set MTemp to the new position

2: set RawMouse to new position

3: set CrsrNew to true

First, we should define our variables:

int             *MTemp;
char            *CrsrNew;

MTemp   = (int *)  0x828;
CrsrNew = (char *) 0x8CE;

Notice that MTemp was declared as an integer, and RawMouse and Mouse were not declared at all. Since the three points are in a row, it is much easier to simply declare the first variable as an integer and increment the pointer to each position to be set. NewPos is passed to our routine, containing the point to which the mouse should be moved in the following code excerpt. Remember that points are stored internally as (v,h) or (row,column), instead of (h,v).

!c

odeexamplestart/* 1 */

for (i=0;i<3;i++) {
 *(MTemp+2*i) = newPos.v;
 *(MTemp+2*i+1) = newPos.h;
}


Once the three points are set, the only task which remains to be done is the setting of the CrsrNew variable. To tell the System that the mouse has moved, the boolean must be set with a non-zero (true) value. Since it is set to -1 by the System, it will be so set here. Any true value should work, however.

/* 2 */

*CrsrNew = -1;

The System routine will realize that the global CrsrNew has been changed, will find the new position in MTemp and RawMouse and will draw the cursor in the new position.

Curse Control

It’s unwise to have your program confuse the user by moving the cursor too dramatically from where he would expect it to appear. If you are in a programming situation which is leading you to move the cursor to where you want it, rather than where the user expects it, you should think twice -- and then think again.

Listing:  Control.c

/*******
 * HandleMouse()
 * Checks the cursor position and calls MousePos if necessary
 *******/
HandleMouse(boundsRect)
Rect  *boundsRect;
{
Point   mousePoint;
Point   newPoint;

 GetMouse(&mousePoint);
 LocalToGlobal(&mousePoint);
 newPoint.h = newPoint.v = -1;
 
 if (mousePoint.h <= boundsRect->left)
 newPoint.h = boundsRect->right - 2;
 else
 if (mousePoint.h >= boundsRect->right - 1)
 newPoint.h = boundsRect->left + 1;
 if (mousePoint.v <= boundsRect->top)
 newPoint.v = boundsRect->bottom - 2;
 else
 if (mousePoint.v >= boundsRect->bottom - 1)
 newPoint.v = boundsRect->top + 1;
 
 if ( (newPoint.h + 1) || (newPoint.v + 1) )
 {
 newPoint.h = (newPoint.h != -1) ? newPoint.h : mousePoint.h;
 newPoint.v = (newPoint.v != -1) ? newPoint.v : mousePoint.v;
 MousePos(newPoint);
 }
}
Listing:  ControlMain.C

/* CursorControl */ /* by Rob Gibson */ /* August 22, 1989. */
/* MacHeaders Included */
/*********  Project file: Control.c  ControlMain.c             Functions.c 
 MacTraps MousePos.c
 Type: APPL Creator: CCTL **********/

#define ControlDialogID 1000
#define nil 0L
/* important dialog items */
enum{   quitItem = 1,   setItem,   topPosItem,     leftPosItem, 
 bottomPosItem,  rightPosItem,   boxItem     };

  /* Our global variables */
DialogPtr ControlDialog;
Rect    boundsRect;

/**InitMacintosh()  Initialize all the managers & memory ***/
InitMacintosh()
{  MaxApplZone();
 InitGraf(&thePort);
 InitFonts();
 FlushEvents(everyEvent, 0);
 InitWindows();
 InitMenus();
 TEInit();
 InitDialogs(0L);
 InitCursor();
} /* end InitMacintosh */

/**GetBounds()  *  * Get the rect specified in dialog  ***/
GetBounds(theDialog)
DialogPtr theDialog;
{  Str255 str;   longdummy;

 boundsRect.top = GetETNum(theDialog, topPosItem);
 boundsRect.left = GetETNum(theDialog, leftPosItem);
 boundsRect.bottom = GetETNum(theDialog, bottomPosItem);
 boundsRect.right = GetETNum(theDialog, rightPosItem);
} /* end GetBounds */

/*TrackRect() Frame old, new bound rects in current GrafPort**/
TrackRect(oldRect, r)
Rect  *oldRect;
Rect  *r;
{  FrameRect(oldRect);
 FrameRect(r);
} /* end TrackRect */

/**DisplayBounds() Display a rect in the dialog*/
DisplayBounds(theRect, theDialog) 
Rect    *theRect;
DialogPtr theDialog;
{  SetETNum(theDialog, topPosItem, (long)theRect->top);
 SetETNum(theDialog, leftPosItem, (long)theRect->left);
 SetETNum(theDialog, bottomPosItem, (long)theRect->bottom);
 SetETNum(theDialog, rightPosItem, (long)theRect->right);
 SelIText(theDialog, topPosItem, 0, 32767);
} /* end DisplayBounds */

/**SetBoundsLoop() User drags to specify new rect**/
SetBoundsLoop(theDialog)
DialogPtr theDialog;
{  Rect oldRect;
 Rect   newRect;
 GrafPtrsavePort;
 GrafPtrdeskPort;
 Point  firstPoint;
 Point  secondPoint;
 Point  lastSecondPoint;

 GetPort(&savePort);
 OpenPort(deskPort = (GrafPtr)NewPtr(sizeof(GrafPort)));
 InitPort(deskPort);
 SetPort(deskPort);
 PenPat(gray);
 PenMode(notPatXor);
 PenSize(2, 2);
 while(!Button());
 GetMouse(&firstPoint);
 newRect.top = lastSecondPoint.v = firstPoint.v;
 newRect.left = lastSecondPoint.h = firstPoint.h;
 newRect.bottom = newRect.right = 0;
 while(Button()) {
 oldRect = newRect;
 GetMouse(&secondPoint);
 /* If the mouse location has changed then track mouse */
 if (secondPoint.v != lastSecondPoint.v || secondPoint.h != lastSecondPoint.h) 
 {
 /* Create a new Rect making sure it is not an empty Rect */
 if (secondPoint.v > firstPoint.v) {
 newRect.top = firstPoint.v;
 newRect.bottom = secondPoint.v;
 }
 else {
 newRect.top = secondPoint.v;
 newRect.bottom = firstPoint.v;
 }
 if (secondPoint.h > firstPoint.h) {
 newRect.left = firstPoint.h;
 newRect.right = secondPoint.h;
 }
 else {
 newRect.left = secondPoint.h;
 newRect.right = firstPoint.h;
 }
 lastSecondPoint = secondPoint;

 TrackRect(&oldRect, &newRect);
 DisplayBounds(&newRect, theDialog);
 }
 }
 FrameRect(&newRect);
 ClosePort(deskPort);
 DisposPtr((Ptr)deskPort);
 PenNormal();
 SetPort(savePort);
 boundsRect = newRect;
 } /* end SetBoundsLoop */

/*HandleControlDialog()  Main event loop  *  ****/
HandleControlDialog(theDialog)
DialogPtr theDialog;
{  EventRecord   event; /*  Filled by GetNextEvent */
 Booleanfinished = false; /*  Are we done? */
 int    chosen;
 char   theChar;

 while (!finished) /*  do this until we selected quit */
 { /* continue with the normal get next event stuff... */
 if (GetNextEvent(everyEvent, &event))
 /*  if there was an event... then  */
 {
 if (event.what == keyDown || event.what == autoKey)
 { 
 theChar = (char) (event.message & charCodeMask);
 switch(theChar) { 
 case ‘Q’:
 case ‘q’:
 case ‘.’:
 chosen = quitItem;
 event.what = 0; /* remove event */
 finished = true;
 ClickButton(theDialog, quitItem, 2);
   break;
   case ‘\t’:
 case ‘\b’: 
 break;
   case ‘\r’:
 case ‘\003’:
 case ‘S’:
 case ‘s’:
 chosen = setItem;
 event.what = 0; /* remove event */
 ClickButton(theDialog, setItem, true);
 SetBoundsLoop(theDialog);
 ClickButton(theDialog, setItem, false);
 break;
 default:
 if (theChar < ‘0’ || theChar > ‘9’)
 event.what = 0;
 break;
 }
 } else if (event.what == updateEvt)
 {
 SetPort(theDialog);
 BeginUpdate(theDialog);
 FrameItem(theDialog, boxItem);
 DrawDialog(theDialog);
 DrawDefaultBtn (theDialog, setItem);
 EndUpdate(theDialog);
 }
   }

 if (!finished) {
 if   (IsDialogEvent(&event))
 if (DialogSelect(&event, &theDialog, &chosen)) {
 GetBounds(theDialog);
 switch (chosen) {
 case 1:
 finished = true;
 break;
 case 2:
 ClickButton(theDialog, setItem, true);
 SetBoundsLoop(theDialog);
 ClickButton(theDialog, setItem, false);
 break;
 default:
 break;
 } /*  end of if switch  */
 } 
 HandleMouse(&boundsRect);
 } /*  end of if (!finished) */
 } /*  of event loop  */

 DisposDialog(theDialog);
} /* end HandleControlDialog */

/*****  * SetUpDialog()  *  * Set up dialog stuff  *  *****/
SetUpDialog() {
 int    itemType;
 Handle Hdl;

 ControlDialog = GetNewDialog(ControlDialogID, nil, -1L);
 CenterWindow(ControlDialog, &screenBits.bounds);
 DisplayBounds(&screenBits.bounds, ControlDialog);
 ShowWindow(ControlDialog);
 boundsRect = screenBits.bounds;
 HandleControlDialog(ControlDialog);
} /* end SetUpDialog */

/*****  * main()  *  * Call the main procedures  *  *****/
main()

{  InitMacintosh();
 SetUpDialog();
} /* end main */
Listings:  Functions.C

/****
 * GetEText()
 * Get text of an ETItem
 ****/
GetEText (theDialog, theItem, s)
DialogPtr theDialog;
inttheItem;
char    *s;
{
 int     theType;
 Handle Hdl;
 Rect box;

 GetDItem (theDialog, theItem, &theType, &Hdl, &box);
 GetIText (Hdl, s);
} /* end GetEText */

/****
 * GetETNum()
 * Get number from an ETItem
 ****/
GetETNum(theDialog, theItem)
DialogPtr theDialog;
inttheItem;
{
 Str255 s;
 long theNum;
 
 GetEText(theDialog, theItem, &s);
 StringToNum(s, &theNum);
 return(theNum);
} /* end GetETNum */

/****
 * SetEText()
 * Set text of an ETItem
 ****/
SetEText (theDialog, theItem, s)
DialogPtr theDialog;
inttheItem;
Str255  s;
{
 int     theType;
 Handle Hdl;
 Rect box;

 GetDItem (theDialog, theItem, &theType, &Hdl, &box);
 SetIText (Hdl, s);
} /* end SetEText */

/****
 * SetETNum()
 * Set number in an ETItem
 ****/
SetETNum(theDialog, theItem, theNum)
DialogPtr theDialog;
inttheItem;
long    theNum;
{
 Str255 s;
 
 NumToString(theNum, s);
 SetEText(theDialog, theItem, &s);
} /* end GetETNum */

/***** LToGRect()  Convert a local rect to global *****/
LToGRect(r)
Rect  *r;
{
 Point  pt1,
 pt2;

 pt1 = topLeft(*r);
 pt2 = botRight(*r);
 LocalToGlobal(&pt1);
 LocalToGlobal(&pt2);
 Pt2Rect(pt1, pt2, r);
} /* end LToGRect */

/*****
 * CenterWindowPoint()
 * Calculates the topleft co-ords of a window,
 * taking screen size into account
 *****/
Point CenterWindowPoint (theRect)
Rect  *theRect;
{
 int    theInd = (screenBits.bounds.bottom<350) ? 3:4;
 Point  thePt;
 int    int1, int2;

 int1=((screenBits.bounds.right-screenBits.bounds.left-theRect->right+theRect->left) 
/ 2);
 int2=((screenBits.bounds.bottom-screenBits.bounds.top-theRect->bottom+theRect->top+20) 
/ theInd);
 SetPt(&thePt, int1, int2);
 return(thePt);
} /* end CenterWindowPoint */

/*****
 * CenterWindow()
 * Centers a dialog or window
 *****/
void CenterWindow(theDialog)
DialogPtr theDialog;
/* Center window - center slightly higher for large screens */
{
 Point  thePt;
 Rect newBounds;

 newBounds = *&theDialog->portRect;
 LToGRect(&newBounds);
 thePt = CenterWindowPoint(&newBounds);
 MoveWindow(theDialog, thePt.h, thePt.v, 0);
} /* end CenterWindow */

/****ClickButton() Simulate a click in a button ****/
ClickButton(theDialog, ID, method) 
/* 0 is off, 1 is on, 2 simulates a click */
DialogPtr theDialog;
intID;
intmethod;
{
 int    itemType;
 Handle item;
 Rect box;
 long ticks;

 GetDItem(theDialog, ID, &itemType, &item, &box);
 HiliteControl((ControlHandle) item, (method >= 1));
 if (method >= 2)
 {
 Delay(8L, &ticks);
 HiliteControl((ControlHandle) item, 0);
 }
} /* end ClickButton */

/****
 * FrameItem()
 * Frame a dialog item in current pen modes
 ****/
void FrameItem (theDialog, item)
DialogPtr theDialog;
intitem;
{
 int    optType;
 Handle btnHdl;
 Rect   optBox;

 SetPort(theDialog);
 GetDItem(theDialog, item, &optType, &btnHdl, &optBox);
 FrameRect(&optBox);
} /* end FrameItem */

/**** DrawDefaultBtn() Outline the default button ****/
void DrawDefaultBtn (theDialog, item)
DialogPtr theDialog;
intitem;
{
 int    optType;
 Handle btnHdl;
 Rect   optBox;

 SetPort(theDialog);
 GetDItem(theDialog, item, &optType, &btnHdl, &optBox);
 PenSize(3, 3);
 InsetRect(&optBox, -4, -4);
 FrameRoundRect(&optBox, 16, 16);
} /* end DrawDefaultBtn */
Listing:  MousePos.C

/********
* MousePos()
* Set the mouse position, August 22, 1989
* by Robert S. T. Gibson for MacTutor
********/
void MousePos(newPos)
Point newPos;
{
 int    *MTemp;
 char *CrsrNew;
 int    i;

 MTemp = (int *)  0x828;  /* Set up our globals... */
 CrsrNew = (char *) 0x8CE;

/* Points are stored as (row, column) or (v, h) in memory...*/
 /* Set our globals... */
 for (i=0;i<3;i++) {
 *(MTemp+2*i) = newPos.v;
 *(MTemp+2*i+1) = newPos.h;
 }
 *CrsrNew = -1;  /* There’s a new position */
}
 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links... | Read more »
Price of Glory unleashes its 1.4 Alpha u...
As much as we all probably dislike Maths as a subject, we do have to hand it to geometry for giving us the good old Hexgrid, home of some of the best strategy games. One such example, Price of Glory, has dropped its 1.4 Alpha update, stocked full... | Read more »
The SLC 2025 kicks off this month to cro...
Ever since the Solo Leveling: Arise Championship 2025 was announced, I have been looking forward to it. The promotional clip they released a month or two back showed crowds going absolutely nuts for the previous competitions, so imagine the... | Read more »
Dive into some early Magicpunk fun as Cr...
Excellent news for fans of steampunk and magic; the Precursor Test for Magicpunk MMORPG Crystal of Atlan opens today. This rather fancy way of saying beta test will remain open until March 5th and is available for PC - boo - and Android devices -... | Read more »
Prepare to get your mind melted as Evang...
If you are a fan of sci-fi shooters and incredibly weird, mind-bending anime series, then you are in for a treat, as Goddess of Victory: Nikke is gearing up for its second collaboration with Evangelion. We were also treated to an upcoming... | Read more »
Square Enix gives with one hand and slap...
We have something of a mixed bag coming over from Square Enix HQ today. Two of their mobile games are revelling in life with new events keeping them alive, whilst another has been thrown onto the ever-growing discard pile Square is building. I... | Read more »
Let the world burn as you have some fest...
It is time to leave the world burning once again as you take a much-needed break from that whole “hero” lark and enjoy some celebrations in Genshin Impact. Version 5.4, Moonlight Amidst Dreams, will see you in Inazuma to attend the Mikawa Flower... | Read more »
Full Moon Over the Abyssal Sea lands on...
Aether Gazer has announced its latest major update, and it is one of the loveliest event names I have ever heard. Full Moon Over the Abyssal Sea is an amazing name, and it comes loaded with two side stories, a new S-grade Modifier, and some fancy... | Read more »
Open your own eatery for all the forest...
Very important question; when you read the title Zoo Restaurant, do you also immediately think of running a restaurant in which you cook Zoo animals as the course? I will just assume yes. Anyway, come June 23rd we will all be able to start up our... | Read more »
Crystal of Atlan opens registration for...
Nuverse was prominently featured in the last month for all the wrong reasons with the USA TikTok debacle, but now it is putting all that behind it and preparing for the Crystal of Atlan beta test. Taking place between February 18th and March 5th,... | Read more »

Price Scanner via MacPrices.net

AT&T is offering a 65% discount on the ne...
AT&T is offering the new iPhone 16e for up to 65% off their monthly finance fee with 36-months of service. No trade-in is required. Discount is applied via monthly bill credits over the 36 month... Read more
Use this code to get a free iPhone 13 at Visi...
For a limited time, use code SWEETDEAL to get a free 128GB iPhone 13 Visible, Verizon’s low-cost wireless cell service, Visible. Deal is valid when you purchase the Visible+ annual plan. Free... Read more
M4 Mac minis on sale for $50-$80 off MSRP at...
B&H Photo has M4 Mac minis in stock and on sale right now for $50 to $80 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses: – M4 Mac mini (16GB/256GB): $549, $50 off... Read more
Buy an iPhone 16 at Boost Mobile and get one...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering one year of free Unlimited service with the purchase of any iPhone 16. Purchase the iPhone at standard MSRP, and then choose... Read more
Get an iPhone 15 for only $299 at Boost Mobil...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 for $299.99 including service with their Unlimited Premium plan (50GB of premium data, $60/month), or $20... Read more
Unreal Mobile is offering $100 off any new iP...
Unreal Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a $100 discount on any new iPhone with service. This includes new iPhone 16 models as well as iPhone 15, 14, 13, and SE... Read more
Apple drops prices on clearance iPhone 14 mod...
With today’s introduction of the new iPhone 16e, Apple has discontinued the iPhone 14, 14 Pro, and SE. In response, Apple has dropped prices on unlocked, Certified Refurbished, iPhone 14 models to a... Read more
B&H has 16-inch M4 Max MacBook Pros on sa...
B&H Photo is offering a $360-$410 discount on new 16-inch MacBook Pros with M4 Max CPUs right now. B&H offers free 1-2 day shipping to most US addresses: – 16″ M4 Max MacBook Pro (36GB/1TB/... Read more
Amazon is offering a $100 discount on the M4...
Amazon has the M4 Pro Mac mini discounted $100 off MSRP right now. Shipping is free. Their price is the lowest currently available for this popular mini: – Mac mini M4 Pro (24GB/512GB): $1299, $100... Read more
B&H continues to offer $150-$220 discount...
B&H Photo has 14-inch M4 MacBook Pros on sale for $150-$220 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – 14″ M4 MacBook Pro (16GB/512GB): $1449, $150 off MSRP – 14″ M4... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.