views:

982

answers:

3

i have an application that records a date/time when the space bar is pressed unfortunately, the window doesn't always have focus, for various reasons. eg virus checker popup, itunes update, windows update, etc

so what i though would be a cool idea is to use a joystick button, then regardless of which window has focus, i can always detect the button press event and record the date/time it was pressed.

now i had a look at a few game tutorials, but they seem to have the joystick polling tied into the screen refresh event, because in a game i guess if the computer is slow and the screen doesn't refresh often, having the joystick button pressed is going to make no difference anyway.

That doesn't really suit my need, so i am looking at running a thread that will poll the joystick every so often

My questions are

  1. is a background thread the best solution
  2. how often should i poll the joystick
  3. what kind of timer should i use to determine the polling frequency.

I would like the responses to be at least equivalent to a keyboard. also need to make sure it doesn't auto-repeat if trigger is held down.

any sample code (C#) appreciated

thanks

alex

+1  A: 

Your best bet would be to create a Timer object on your form, and tie the joystick check to the Tick event.

I've also found that running simple stuff like this every 100ms (10 times a second) has a negligible effect on CPU usage.

Chris
+1  A: 

If you want to go for polling the joystick just because you are not able to capture the keyboard event, I think you need to re-work your strategy.

Even if your form doesn't have the focus there are ways that you can make sure you know of the keyboard state.

  1. You could set up a system wide keyboard hook which can be done in C# using the SetWindowsHookEx API call.

This is delving a little in unmanaged code and Windows API, but I think it's a better idea than polling a joystick cause you won't need to add a joystick to your computer just because you need to capture datetime at the press of a spacebar.

Do a little search on google for keyboard hooks in C#. It's easier than many people believe.

I don't think using a timer object to do this is a good idea at all. Cause I believe you said you need to do it at the press of a key.

Cyril Gupta
+1  A: 

Use something like AHK (Auto HotKey) it is a simple language that can be compiled to an EXE and is designed for automating the keyboard and mouse, I'm not 100% sure how well it works with a joystick, but I'm sure it's possible they managed to write some stuff for the wii remotes.

Also the IRC Channel and Forums always have people willing to help if need be.

Unkwntech