{steinsoft.net}
 
 
 
 
 
Home/News
Code Snippets
Board
Projects
What's That?
I am using it actively
I planning to use/learn it
I don't plan to lean/use it
5th option
Leipzig
Home :: Programming :: Code Snippets :: MfcWin :: Using a Joystick

[ Using a Joystick ]

Welcome to another Mfc/Win snippet! This time I will show you how to get the joystick's position and its button states. As always it is really easy if you know how to do it..

The one and only function you need is joyGetPos(..) from mmystem.h. Here it is:

MMRESULT joyGetPos(UINT uJoyID, LPJOYINFO pji);

uJoyId is the joystick you want to get info about. This can be either the first - JOYSTICKID1 - or the second - JOYSTICKID2 - joystick. pji is a a pointer to a JOYINFO structure where the joystick's state will be saved to.

typdef struct
{
UINT wXpos;
UINT wYpos;
UINT wZpos;
UINT wButtons;
} JOYINFO;

wXpos holds the X-Position of the joystick (from left to right), wYpos the Y-Position (from top to bottom) and wZpos the position of the third axis most often the throttle. These positions range from 0 to 65536 with 32768 being the center. wButtons holds the ORed ("|") buttons that are pressed at the moment. These can be: JOY_BUTTON1, JOY_BUTTON_2, JOY_BUTTON_3 and JOY_BUTTON_4.

joyGetPos(..) returns JOYERR_NOERROR if no error has occured. That's enough theory. Let's take a look at a real example:

//Header needed for the joystick functionality
#include<mmsytem.h>
 
void CheckJoystick()
{
   JOYINFO joystickInfo;
   //Update info using the first joystick
   if (joyGetPos(JOYSTICKID1,&joystickInfo) == JOYERR_NOERROR)
   {
      //Is second button pressed??
      if (joystickInfo.wButtons & JOY_BUTTON2)
      {
         //yes.. it is
         MessageBox(NULL,"Second Btn down!","Msg",MB_OK);
      }
  
      //Do something with the joy's throttle position
      DoSomething(joystickInfo.wZpos);
   }
}

That's it! Don't forget to add winmm.lib to you project. Otherwise there'll be an error. If you have questions, visit the message board or m@il me. Happy Coding!

 Last edited 2004-06-24 15:19:22 by André Stein - printable version
» copyright by andré stein
» using stCM v1.0
» steinsoft.net revision 5.0