1. 程式人生 > >Unity鍵盤鉤子

Unity鍵盤鉤子

http://blog.csdn.net/qq452626100/article/details/52398830

private static int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
{
	if (nCode == HC_ACTION	)
	{
		var kc = (KeyCode)(wParam+97-65);

		// https://msdn.microsoft.com/en-us/library/windows/desktop/ms644984(v=vs.85).aspx
		int int32Param = lParam.ToInt32();
		var repeat_count	= (ushort) (int32Param&		0xFFFF); //0 - 15	The repeat count.The value is the number of times the keystroke is repeated as a result of the user's holding down the key.
		var scan_code		= (ushort)((int32Param&	  0xFF0000)>>16); //16 - 23The scan code.The value depends on the OEM.
		var extended_key	= 0!=  ((int32Param&  0x1000000)>>24); //24 Indicates whether the key is an extended key, such as a function key or a key on the numeric keypad.The value is 1 if the key is an extended key; otherwise, it is 0.
		var reserved		= (ushort)((int32Param&	0x1E000000)>>25); //25 - 28Reserved.
		var context_code	= 0!=  ((int32Param&	0x20000000)>>29); //29The context code.The value is 1 if the ALT key is down; otherwise, it is 0.
		var previous_key_state=0!= ((int32Param&	0x40000000)>>30); //30The previous key state.The value is 1 if the key is down before the message is sent; it is 0 if the key is up.
		var transition_state= 0!=  ((int32Param&	0x80000000)>>31);//31	The transition state. The value is 0 if the key is being pressed and 1 if it is being released.

		if( !previous_key_state && !transition_state)//有鍵按下
		{
			Debug.Log ("鉤子鍵盤按下:"+kc);
		}
		else if( previous_key_state && transition_state)
		{
			Debug.Log ("鉤子鍵盤擡起:"+kc);
		}
		return 1;
	}

	return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam); 

}