Multithreaded Input Detection

I’m working on a project that uses a Bluetooth signal sending data on the amount of force detected by a sensor. We’re using that to move our character. We pushed all of the reading from the sensor to another thread to significantly cut down on a bottleneck in our code.

An issue came up where if other developers didn’t have the sensor attached they wouldn’t be able to test their changes to the project. So, I wrote up a mock object that gets used when no sensor is available. The only thing is I’d prefer to be able to use keypresses to simulate different input speeds, without needing the sensor. The only thing is Input.GetKey can only be called on the main thread. Since this is only used in the editor, and it wouldn’t make sense to chanage the ReadData() interface just for debugging is there anyway to just use plain C# to detect keypresses on other threads?

Everything I’ve found on it seems to require Windows Forms, and I don’t think it’s the best idea to add that assembly to the project.

Well, when you are on windows you can always use the win API directly. Either GetKeyState or GetKeyboardState. If you don’t know how to use an external native code method, take a look at pinvoke.net(GetKeyState) (GetKeyboardState).

If you are on a different system, i doubt there’s a general solution without using Windows Forms of something like that. So for Mac and Linux you have to find equivalent native methods.

This is the code I ended up using, in case anyone else needs a quick reference.

[DllImport("USER32.dll")]
		static extern short GetKeyState(VirtualKeyStates nVirtKey);

		public bool IsKeyPressed(VirtualKeyStates testKey)
		{
			bool keyPressed;
			short result = GetKeyState(testKey);
			switch (result)
			{
				case 0:
					// Not pressed and not toggled on.
					keyPressed = false;
					break;

				case 1:
					// Not pressed, but toggled on
					keyPressed = false;
					break;

				default:
					// Pressed (and may be toggled on)
					keyPressed = true;
					break;
			}
			return keyPressed;
		}