gluPickMatrix problem.. please help me

Hello all. I am writing a little program where I have 10 spheres on screen, they are animated. I would like to get the user chose by controlling the mouse, so I have written a pluPickMatrix routing. It doesn’t work… I am using BCB6
Here is the code, copyed by red book:

#define BUFSIZE 512
void __fastcall TFormGL::FormMouseDown(TObject *Sender,
TMouseButton Button, TShiftState Shift, int X, int Y)
GLuint selectBuf[BUFSIZE];
GLint hits;
GLint viewport[4];

glGetIntegerv (GL_VIEWPORT, viewport);

glSelectBuffer (BUFSIZE, selectBuf);
(void) glRenderMode (GL_SELECT);


glMatrixMode (GL_PROJECTION);
glPushMatrix ();
    glLoadIdentity ();

/* create 5x5 pixel picking region near cursor location */
gluPickMatrix((GLdouble) X, (GLdouble) (viewport[3] - Y), 5.0, 5.0, viewport);
gluOrtho2D (0.0, 3.0, 0.0, 3.0);
DrawObjects (GL_SELECT); //
glPopMatrix ();
glFlush ();

hits = glRenderMode (GL_RENDER);
Form2->Label1->Caption = hits;

When i click the mouse button, the program ends with “invalid floating point operation”. I have inserted it in another 3d animation, it work but it select wrong. Sometimes it get 1 selected and sometimes it get 0 selected.
Any help ?
Thank you very much

Try to insert glMatrixMode(GL_MODELVIEW) right before you draw your objects and glMatrixMode(GL_PROJECTION) right after the drawing routine.

I think its best to always have the modelview matrix as the active matrix. This keeps your program in a consistent state. Hence you should consider switching to the modelview matrix again after poping the projection matrix stack.