TweetFollow Us on Twitter

Beginning Windows
Volume Number:2
Issue Number:7
Column Tag:ABC's of C

Beginning Windows

By Bob Gordon, Apropos Publication Services, Contributing Editor

Probably the most visible part of the Macintosh user interface is the window. Since we can't build much of an application without showing something on the screen, we will begin to examine how to use the Macintosh Window Manager. At the same time, we'll take a look at the C preprocessor, the if-statement, and review the topics from last month-the Event Manager, structures, and the case statement.

Preprocess Your Code

The C preprocessor provides a variety of useful services. We saw last month how to use the #define to provide a shorthand name by which to refer to a structure. These 'define' statements and other data structures can be stored in a seperate ".h" file and included into our source code at compile time. We can create our own new ".h" file to reduce some of C's more arcane symbols. We will call this file "abc.h".

/* abc.h 
 *
 * Local definitions to improve readability
 *
 */
 
#define True1
#define False  0
#define Nil 0
#define and &&
#define or||
#define not !
#define equals ==
#define notequal !=

extern char *PtoCstr(); /* from stdio.h  */
extern char *CtoPstr();

The first three definitions provide some standard constants. C has no boolean type, but it is a good idea to use labeled constants rather than numbers when doing logic. It makes the code easier to follow. "Nil" is used with pointers. Assign a pointer Nil when you don't want it to point anywhere. C guarantees that a pointer can never point to zero, so this is a safe initialization value.

We then have replacements for the logical operation symbols. Admittedly, these take longer to type, but they are much easier to read (they are especially helpful if you must show your code to someone who doesn't use C), and they are safer. A very popular C bug is to leave one of the equal signs out of the equality operator (see top of next column):

 if (a = b)
    code;

instead of

 if (a == b)
    code;

The first is a perfectly legal C if-statement: it assigns the value of b to a, then if a is non-zero, the code is executed. The second executes the code only if the value of a equals the value of b. The cleverness of this bug is that not only is it legal, but many times it is what you want to do. Using "equals" instead of "==" makes it much less likely to change the meaning of a line by a typo, and it makes it much easier to find.

The last two entries are the Pascal-to-C and C-to-Pascal string conversion utilities. These are normally defined in the stdio.h file, but since we are not including that file, we can put them here. Remember, C and Pascal strings are different, so if we send a string to a Toolbox routine, it must be a Pascal string. These are the functions that Mac C has. Other compilers may have similar functions (Aztec C calls these ctop() and ptoc()) or they will do the conversion automatically. Check your documentation and place the appropriate functions in abc.h so you can use them without repeating the external declarations in every source file.

To use abc.h, just have it as one of the include files at the begining of a source file. All the definitions will then be available. We may add other definitions later.

By the way, the May 1986 Byte has an article called "Easy C" that describes a considerably expanded set of preproccessor definitions. The authors replace many of the standard C terms with new ones in an effort to increase readability and reduce errors.

Fig. 1 Program output, window highlited.

if-then-else

There are several if-statements in the sample program. The if-statement is C's other branching construct. Its general form is:

if (expression)
 statement;

if (expression)
 statement;
else    /* shows optional else clause */
 statement;

If the experession evaluates to a non-zero value, the statement is executed. If the expression evaluates to zero and an else is present, the statement following the else is executed. If no else is present, execution continues after the if.

If-statements may be nested, but the relation of else to if may be ambigous:

 if (expression)
 if (another expression)
 statement;
 else
 statement;

Does the else go with the first if or the second? The layout on the page says it will go with the first, but the compiler will place it with the second as it is closer. Use braces to clear up ambiguities:

 if (expression)
 {
 if (another expression)
 statement;
 }
 else
 statement;

Fig. 2 Mouse click outside the window

Fig. 3. Cmd T changes title name

Structures, Functions, and Pointers

The only other C issue we need to deal with is how to get structures in and out of functions. The original definition of C did not allow functions to receive structures as parameters or return them (the new ANSI standard does allow this, check your compiler). A function could, however, receive or return a pointer to a structure. In C a pointer is simply an address, and you can get the address of a variable with the address operator (the ampersand). In the example, theEvent is an EventRecord structure to get the next event from the Event Manager; the pointer (or address) to the EventRecord is specified as &theEvent:

 GetNextEvent(everyEvent,&theEvent);

This passes the address of theEvent to GetNextEvent, by specifying it as &theEvent. This works well with all C compilers, but it does not work in all cases with Toolbox functions. The problem is that Pascal allows structures (records) to be passed as parameters, as well as by address. On the Mac, only structures of four or fewer bytes are passed as parameters; longer structures are passed by address. There is one structure of four bytes, the Point, which we saw last month. Mac C handles this automatically. They define the Point as one of the argument types that can be passed to Toolbox routines. If you are using Mac C, pass the address of the Point. Aztec C, on the other hand, uses a special function, pass() to pass points, as shown below:

FindWindow(pass(er.where), &whichWindow); /*aztec */

Finally, since structures are often used with pointers, C has a special operator to access a member of a structure given a pointer to the structure. If er is an EventRecord and erp is a pointer to an Event Record, the what field is accessed by:

 er.what/* the what member */
 erp->what/* the what member */
 (*erp).what/* the what member */

The last example shows the indirection operator (the asterisk). It yields the value at the address contained in the variable. The structure pointer operator (->) is much easier to read.

Putting a Window on the Screen

The example program this month puts a window on the screen, changes its title, and responds to certain mouse commands. The program deals with only one window and does not include the change size command as multiple windows and changing the size involves accessing the Memory Manager. We'll add these features after we cover it.

The program consists of five routines:

main()

Does initialization and calls the main event loop routine. InitWindows() must be done if you want to use any of the Window Manager routines. See what happens if you do not InitCursor(). The dragbounds rectangle limits the range of DragWindow(): it ensures the window does not fall off the screen. Note that I used the preprocessor to define Screen. This was done simply to avoid typing QD->screenBits.bounds. If we find we need to use QD->screenBits.bounds a lot, we can add it to abc.h.

dowindow()

The dowindow() routine creates a new window on the desktop. As such, it is primarily a call to the toolbox trap NewWindow(), which returns a window pointer to the newly created window structure.

There are several potential trouble spots in NewWindow(). First, the window record (windowRec) must be static. I made it a global. Notice the use of the string conversion routines. See what happens if you don't convert the string back. The parameter, (WindowPtr)-1, is the behind parameter. We wish to place our new window in front of all other windows. To do this we must set the pointer to -1. The construct (WindowPtr) casts the -1 into the type WindowPtr. I expect there would be a serious problem if you left the (WindowPtr) out. Try it. Parameter conversion in C is called 'casting'. By enclosing a parameter type such as WindowPtr in parenthesis, followed by a variable, that variable, in this case, -1, is converted into the same parameter type, in this case a four byte address. Hence, (WindowPtr)-1 is just a fancy way of defining -1 as a long int. Finally, the last parameter is refCon, a value passed to the Window Manager for the application's own use. I'm just passing a zero because I don't have anything to do with it at this time. refCon, though is a long. Mac C seems to pass this correctly, but other compilers may require the value to be explicitly a long. This is another case where things that look correct will not work correctly. To make a constant explictly a long, place an "L" after it (0L).

eventloop()

This is similar to last month's program. Here the EventRecord is local to eventloop(). I only wanted to check the keyDown and mouseDown events so I could have changed the event mask. You might rewrite it that way. If you are reading along in Using the Macintosh Toolbox in C, you will notice that they have this program as one function. I try to keep things fairly small.

dokey()

Here we respond to all the keyDown events. Most of the toolbox routines are fairly straight forward. Each window function receives a window pointer as a parameter. What we are checking for is our menu of command keys. Assuming we have a window opened, then our dokey() routine defines the command keys we will respond to:

Key Function

cmd m make a window ( call dowindow() )

cmd x kill the window (close it)

cmd s show a hidden window

cmd h hide a shown window

cmd t change the window's title

cmd q quit by returning to the finder

We get the keyboard character by extracting it from the message portion of our event record and masking it with a mask that guarantees we only get command key sequences. Then we extract the ascii value of the key sans command key, and check it against the above table of allowed keystrokes. We check for the m key first so we can make a new window if one does not already exist. After that, our switch construct can list each of our key commands knowing that a valid window is present.

domouse()

domouse handles the mouseDown events. First it must determine where the mouse is. The function FindWindow() does this and returns a window code and a pointer to the relevant window. Note the use of the address operator to pass the Point where member. Most of the window functions here are straight forward. TrackGoAway() retains control as long as the mouse button is down and lights the go-away box if the mouse pointer is in it.

Note that I am always calling DrawGrowIcon() after each Window Manager call. This is not really necessary because we're not doing anything with the grow box. Try taking it out.

Final Notes

We've only touched on part of the Window Manager functions. Some will wait until we've covered memory management, others until we've covered resources. Placing things like window definitions inside resource files helps structure the program and makes the user interface components easier to modify and port to different languages (human, not computer). Since this column is about C, I'm going to avoid using resources so we can use the C functions as much as possible. Also, resources present an extra step in getting a program to run, and while we're learning how to do things, we don't need the extra steps. To learn more about resources, read Joel West's "Resource Roundup" series.

Next month we'll move to menus. Rather than use the program in Using the Macintosh Toolbox with C, I will add menus to this one. Now all we have to do is figure out something interesting to put in our windows. Suggestions are welcome.

/* window manager demonstration 
 * base on program in 
 * Using Macintosh Toolbox with C
 * page 70
 */
 
 /* Here are our include files */
 
 #include "abc.h"/* Our own defines */
 #include "Events.h" /* also includes Macdefs.h */
 #include "Window.h" /* also includes Quickdraw.h, which 
 in turn requires M68KLIB.D  */
 
 /* Here are our defines */
 
 #defineScreen   QD->screenBits.bounds
 #definecharCodeMask 0x000000FF
 
 /* Here are our Global variables */
 
 WindowPtrtheWindow;
 WindowRecord  windowRec;
 Rect   dragbound;
 Rect   limitRect;
 
main()
{
 InitWindows();
 InitCursor();
 FlushEvents(everyEvent);
 
 /* Initialize our global variables */
 
 theWindow = Nil;/*indicates no window */
 SetRect(&dragbound,
 Screen.left + 4,
 Screen.top + 24,
      Screen.right - 4,
 Screen.bottom - 4);
 SetRect(&limitRect,60,40,
 Screen.right - Screen.left - 4,
 Screen.bottom - Screen.top - 24);
 
 dowindow();/* make new window */  
 eventloop();    /* check for events */
}

dowindow()
{
char    *title;  /* first title for window */
Rect    boundsRect;
 
if (not theWindow) /* if no window exists, make one */
 {
 title = "ABC Window";
 SetRect(&boundsRect,50,50,300,150);
 theWindow = NewWindow(windowRec, &boundsRect, CtoPstr(title),True,documentProc, 
(WindowPtr) -1, True, 0);
 DrawGrowIcon(theWindow);
 PtoCstr(title);
 }
}

eventloop()
{
EventRecord theEvent;

while(True)
 if (GetNextEvent(everyEvent,&theEvent))
 switch(theEvent.what)    
 { 
 case keyDown:   
 dokey(&theEvent); /* check key, */
 break;
 case mouseDown:
 domouse(&theEvent); /* mouse down evts */
 break;
 default:
 break;
 }
}

dokey(er)
 EventRecord*er;
{
 char   c;/* character from message */
 char   *title2; /* second title for window */
 
 if (not(er->modifiers & cmdKey))  
 return;/* only pay attention to cmd keys */
 /* extract character, lower 8 bits */
 c = er->message & charCodeMask; 
 if (c equals 'q' or c equals 'Q') /* 'q' quits program */
 ExitToShell();  
 
 if (not theWindow)
 {
 if (c equals 'm' or c equals 'M')
 {
 dowindow();
 return;
 }
 else
 {
 SysBeep(1);
 return;
 }
 }
 /* Have a window, so try commands */
 switch (c)
 {
 case 'x':
 case 'X':
 CloseWindow(theWindow);
 theWindow = Nil;
 break;
 case 's':
 case 'S':
 ShowWindow(theWindow);
 DrawGrowIcon(theWindow);
 break;
 case 'h':
 case 'H':
 HideWindow(theWindow);
 break;
 case 't':
 case 'T':
 title2 = "A Different Title";
 SetWTitle(theWindow, CtoPstr(title2));
 PtoCstr(title2);
 break;
 default:
 SysBeep(1);
 break;
 }
}

domouse(er)
 EventRecord*er;
{
 short  windowcode;
 WindowPtrwhichWindow;
 short  ingo;
 long   size;
 
 windowcode = FindWindow(&er->where, &whichWindow);
 switch (windowcode)
 {
 case inDesk:
 if (theWindow notequal 0)
 {
 HiliteWindow(theWindow, False);
 DrawGrowIcon(theWindow);
 }
 else
 ExitToShell();  /* exit if no window */
 break;
 case inMenuBar:
 SysBeep(1);
 break;
 case inSysWindow:
 SysBeep(1);
 break;
 case inContent:
 HiliteWindow(whichWindow,True);
 DrawGrowIcon(theWindow);
 break;
 case inDrag:
 DragWindow(whichWindow, &er->where, &dragbound);
 DrawGrowIcon(theWindow);
 break;
 case inGrow:
 /* not included this month */
 break;
 case inGoAway:
 ingo = TrackGoAway(whichWindow, &er->where);
 if (ingo)
 {
 CloseWindow(whichWindow);
 theWindow = Nil;
 }
 break;
 }
}

Why Did They Do it Dept.?

Here is another little oops for Apple's new Mac Plus. It seems on the old ROMS, if you held down a menu item with the mouse and then did a cmd-shift-3 to take a paint snapshot, when you released the mouse, the menu remained down while the screen was captured in a paint document. This became a great feature because it allowed you to document your menu bar selections. In the new ROMs, this feature no longer works. When you release the mouse, the menu snaps up and then the screen is captured. The result is that there is no way to document your menu bar selections anymore. Boo! MacTutor will pay $250 for the best article that provides a convenient patch for Apple's blunder.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Whitethorn Games combines two completely...
If you have ever gone fishing then you know that it is a lesson in patience, sitting around waiting for a bite that may never come. Well, that's because you have been doing it wrong, since as Whitehorn Games now demonstrates in new release Skate... | Read more »
Call of Duty Warzone is a Waiting Simula...
It's always fun when a splashy multiplayer game comes to mobile because they are few and far between, so I was excited to see the notification about Call of Duty: Warzone Mobile (finally) launching last week and wanted to try it out. As someone who... | Read more »
Albion Online introduces some massive ne...
Sandbox Interactive has announced an upcoming update to its flagship MMORPG Albion Online, containing massive updates to its existing guild Vs guild systems. Someone clearly rewatched the Helms Deep battle in Lord of the Rings and spent the next... | Read more »
Chucklefish announces launch date of the...
Chucklefish, the indie London-based team we probably all know from developing Terraria or their stint publishing Stardew Valley, has revealed the mobile release date for roguelike deck-builder Wildfrost. Developed by Gaziter and Deadpan Games, the... | Read more »
Netmarble opens pre-registration for act...
It has been close to three years since Netmarble announced they would be adapting the smash series Solo Leveling into a video game, and at last, they have announced the opening of pre-orders for Solo Leveling: Arise. [Read more] | Read more »
PUBG Mobile celebrates sixth anniversary...
For the past six years, PUBG Mobile has been one of the most popular shooters you can play in the palm of your hand, and Krafton is celebrating this milestone and many years of ups by teaming up with hit music man JVKE to create a special song for... | Read more »
ASTRA: Knights of Veda refuse to pump th...
In perhaps the most recent example of being incredibly eager, ASTRA: Knights of Veda has dropped its second collaboration with South Korean boyband Seventeen, named so as it consists of exactly thirteen members and a video collaboration with Lee... | Read more »
Collect all your cats and caterpillars a...
If you are growing tired of trying to build a town with your phone by using it as a tiny, ineffectual shover then fear no longer, as Independent Arts Software has announced the upcoming release of Construction Simulator 4, from the critically... | Read more »
Backbone complete its lineup of 2nd Gene...
With all the ports of big AAA games that have been coming to mobile, it is becoming more convenient than ever to own a good controller, and to help with this Backbone has announced the completion of their 2nd generation product lineup with their... | Read more »
Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »

Price Scanner via MacPrices.net

B&H has Apple’s 13-inch M2 MacBook Airs o...
B&H Photo has 13″ MacBook Airs with M2 CPUs and 256GB of storage in stock and on sale for up to $150 off Apple’s new MSRP, starting at only $849. Free 1-2 day delivery is available to most US... Read more
M2 Mac minis on sale for $100-$200 off MSRP,...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100-$200 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $... Read more
Mac Studios with M2 Max and M2 Ultra CPUs on...
B&H Photo has standard-configuration Mac Studios with Apple’s M2 Max & Ultra CPUs in stock today and on Easter sale for $200 off MSRP. Their prices are the lowest available for these models... Read more
Deal Alert! B&H Photo has Apple’s 14-inch...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on sale for $200-$300 off MSRP, starting at only $1399. B&H offers free 1-2 day delivery to most US addresses: – 14″ 8... Read more
Department Of Justice Sets Sights On Apple In...
NEWS – The ball has finally dropped on the big Apple. The ball (metaphorically speaking) — an antitrust lawsuit filed in the U.S. on March 21 by the Department of Justice (DOJ) — came down following... Read more
New 13-inch M3 MacBook Air on sale for $999,...
Amazon has Apple’s new 13″ M3 MacBook Air on sale for $100 off MSRP for the first time, now just $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD/Space Gray): $999 $100 off MSRP... Read more
Amazon has Apple’s 9th-generation WiFi iPads...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Discounted 14-inch M3 MacBook Pros with 16GB...
Apple retailer Expercom has 14″ MacBook Pros with M3 CPUs and 16GB of standard memory discounted by up to $120 off Apple’s MSRP: – 14″ M3 MacBook Pro (16GB RAM/256GB SSD): $1691.06 $108 off MSRP – 14... Read more
Clearance 15-inch M2 MacBook Airs on sale for...
B&H Photo has Apple’s 15″ MacBook Airs with M2 CPUs (8GB RAM/256GB SSD) in stock today and on clearance sale for $999 in all four colors. Free 1-2 delivery is available to most US addresses.... Read more
Clearance 13-inch M1 MacBook Airs drop to onl...
B&H has Apple’s base 13″ M1 MacBook Air (Space Gray, Silver, & Gold) in stock and on clearance sale today for $300 off MSRP, only $699. Free 1-2 day shipping is available to most addresses in... Read more

Jobs Board

Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Business Analyst | *Apple* Pay - Banco Popu...
Business Analyst | Apple PayApply now " Apply now + Apply Now + Start applying with LinkedIn Start + Please wait Date:Mar 19, 2024 Location: San Juan-Cupey, PR Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.