April 5, 2008
WikiHello Lines
Hello Lines
Step by Step
We have a main function in the program that runs continuously as we have in Java.
void main( void ) {
Initialize();
doEventLoop();
}
In the top of the code we are declaring two global vars. One is windRect and its type is Rect. The other is ourWindow whose type is WindowPtr. In our initialization function, first we are setting the rectangle window by SetRect function. Then creating our window by calling NewCWindow. Finally after checking if it is there we are calling ShowWindow and SetPortWindowPort function. Let’s check out our initialize function:
void Initialize(void){
SetRect(&windRect,100,100,740,580);
InitCursor();
ourWindow = NewCWindow( 0L, &windRect, "\pHello Lines", true,
noGrowDocProc,(WindowPtr)-1L, true, 0L );
if ( ourWindow == nil ) ExitToShell();
ShowWindow( ourWindow );
SetPortWindowPort( ourWindow );
}
Above code make sures we set up our window and set our color port to be displayed on our window! Then comes the doEventLoop function that has been called again and again in the main function of our program. doEventLoop contains lots of nonsense things that I haven’t explored yet. We are calling drawLine function at the end of this loop though.
void doEventLoop() {
EventRecord anEvent;
WindowPtr evtWind;
short clickArea;
Rect screenRect;
Point thePoint;
while (TRUE) {
if (WaitNextEvent( everyEvent, &anEvent, 0, nil )) {
if (anEvent.what == mouseDown) {
clickArea = FindWindow( anEvent.where, &evtWind );
if (clickArea == inDrag) {
GetRegionBounds( GetGrayRgn(), &screenRect );
DragWindow( evtWind, anEvent.where, &screenRect );
} else if (clickArea == inContent) {
if (evtWind != FrontWindow())
SelectWindow( evtWind );
else {
thePoint = anEvent.where;
GlobalToLocal( &thePoint );
//Handle click in window content here
}
}
else if (clickArea == inGoAway)
if (TrackGoAway( evtWind, anEvent.where ))
return;
}
}
DrawLine(); // this is our main drawing function.
}
}
Setting a local var Rect to pass our address of rect to the GetPortBounds function which looks like necessary. Then setting the port we are using for the window, and then getting the boundaries of the port, and getting the mouse coordinates. Luckily enough we have mouse.h and mouse.y member variables for the mouse struct. MoveTo and LineTo are default drawing functions we are used to seeing in almost every language.
void DrawLine( ){
Rect pictureRect;
Point mouse;
SetPortWindowPort(ourWindow);
GetPortBounds(GetWindowPort(ourWindow), &pictureRect);
GetMouse(&mouse);
if(PtInRect(mouse,&pictureRect)) {
MoveTo( oldx, oldy );
LineTo( mouse.h,mouse.v );
oldx = mouse.h;
oldy= mouse.v;
}
}
Continue Reading
Back to Archive