/// <summary> /// Waits until a given event on a key occurs. /// </summary> /// <param name="key">The key.</param> /// <param name="state">The state. KeyState.None indicates any state</param> /// <param name="timeout">The timeout.</param> /// <returns></returns> /// <exception cref="InvalidOperationException"> /// The " + nameof(InputManager) + " needs to be initialized before it can /// execute this method. /// </exception> /// <exception cref="ArgumentException">VirtualKeyCode.INVALID is not supported by this method. - key</exception> public bool WaitForEvent(VirtualKeyCode key, KeyState state = KeyState.None, int timeout = -1) { if (!IsInitialized) { throw new InvalidOperationException("The " + nameof(InputManager) + " needs to be initialized before it can execute this method."); } if (key == VirtualKeyCode.Invalid) { throw new ArgumentException("VirtualKeyCode.INVALID is not supported by this method.", nameof(key)); } var threadLock = new object(); KeyStateChangedEventHandler handler = (curKey, curState) => { if (curKey != key) { return; } if (curState != state && state != KeyState.None) { return; } if (!Monitor.TryEnter(threadLock)) { return; } // someone else has the lock Monitor.PulseAll(threadLock); Monitor.Exit(threadLock); }; bool result; RegisterEvent(key, handler); Monitor.Enter(threadLock); if (timeout < 0) { Monitor.Wait(threadLock); result = true; } else { result = Monitor.Wait(threadLock, timeout); } UnregisterEvent(key, handler); return(result); }
/// <summary> /// Unregisters an event (callback) for certain keys. /// </summary> /// <param name="key">The key.</param> /// <param name="handler">The handler.</param> /// <returns></returns> /// <exception cref="InvalidOperationException"> /// The " + nameof(InputManager) + " needs to be initialized before it can /// execute this method. /// </exception> /// <exception cref="ArgumentException">VirtualKeyCode.INVALID is not supported by this method. - key</exception> /// <exception cref="ArgumentNullException">handler</exception> public bool UnregisterEvent(VirtualKeyCode key, KeyStateChangedEventHandler handler) { if (!IsInitialized) { throw new InvalidOperationException("The " + nameof(InputManager) + " needs to be initialized before it can execute this method."); } if (key == VirtualKeyCode.Invalid) { throw new ArgumentException("VirtualKeyCode.INVALID is not supported by this method.", nameof(key)); } if (handler == null) { throw new ArgumentNullException(nameof(handler)); } lock (_lockObject) { return(_keyStateChangedCallbacks[key].Remove(handler)); } }