View Python: Getting Keyboard & Mouse Input
In C4D’s API, there’s two methods available to get keyboard and mouse input, GetInputState and GetInputEvent. Both methods are available globally (C++ c4d_gui, Python c4d.gui), and within the GeDialog and GeUserArea classes. These methods are not available in COFFEE.
GetInputState allows you to poll the current state of an input device (see if the mouse button is currently down, or a key is currently pressed)
GetInputEvent gets the next event for a device in the event queue.
In both cases, the results are stored in a BaseContainer, and the values are keyed based on the constants which can be found in the Input Events page of the C++ or Python API
Python: Detect if a specific key is pressed when a script is executed:
import c4d def main(): # Check any one key bc = c4d.BaseContainer() if c4d.gui.GetInputState(c4d.BFM_INPUT_KEYBOARD,c4d.KEY_F10,bc): if bc[c4d.BFM_INPUT_VALUE] == 1: print "F10 PRESSED" else: print "F10 NOT PRESSED"
Python: Detect which modifiers are pressed when a script is executed:
import c4d def main(): # Check all keys bc = c4d.BaseContainer() if c4d.gui.GetInputState(c4d.BFM_INPUT_KEYBOARD,c4d.BFM_INPUT_CHANNEL,bc): print "Qualifier Bitwise:",bc[c4d.BFM_INPUT_QUALIFIER] if bc[c4d.BFM_INPUT_QUALIFIER] & c4d.QSHIFT: print "SHIFT PRESSED" if bc[c4d.BFM_INPUT_QUALIFIER] & c4d.QCTRL: print "CONTROL PRESSED" if bc[c4d.BFM_INPUT_QUALIFIER] & c4d.QALT: print "ALT PRESSED"
Note that in this example, the value of BFM_INPUT_QUALIFIER is a bitmask. Bitmasks allow multiple binary states to be represented in a single integer value. In a bitmask, each binary “slot” can on or off (1 or 0). The value in the first “slot” is multiplied by 1 (20), the second “slot” is multiplied by 2 (21), the third “slot” by 4 (22), and so on. Those values are added together to get the integer value.
To test if a specific “slot” is true (the modifier is pressed), you use a bitwise AND operator, which in Python and C++ is a single ampersand. You test the integer against the value of that slot, which is represented here by the constants QSHIFT, QCTRL and QALT.