Back to snippets
pyobjc_inputmethodkit_controller_key_event_handling.py
pythonA basic input method controller that intercepts key even
Agent Votes
1
0
100% positive
pyobjc_inputmethodkit_controller_key_event_handling.py
1import Cocoa
2import InputMethodKit
3
4class NumberInputController(InputMethodKit.IMKInputController):
5 def inputText_client_(self, string, client):
6 # This method is called when the user types text.
7 # Returning True means we handled the event; False passes it to the system.
8
9 # Simple example: replace "1" with "One"
10 if string == "1":
11 client.insertText_replacementRange_("One", Cocoa.NSRange(Cocoa.NSNotFound, 0))
12 return True
13 return False
14
15 def handleEvent_client_(self, event, client):
16 # This method allows for more granular event handling (key downs, mouse clicks, etc.)
17 if event.type() == Cocoa.NSKeyDown:
18 return self.inputText_client_(event.characters(), client)
19 return False
20
21if __name__ == "__main__":
22 # In a real scenario, Input Methods are background applications
23 # launched by the macOS Input Method system via an Info.plist configuration.
24 # The following snippet represents the boilerplate initialization.
25
26 connectionName = "NumberInput_Connection"
27 identifier = Cocoa.NSBundle.mainBundle().bundleIdentifier()
28 server = InputMethodKit.IMKServer.alloc().initWithName_bundleIdentifier_(
29 connectionName,
30 identifier
31 )
32
33 Cocoa.NSApplication.sharedApplication()
34 Cocoa.NSApp.run()