My goal is to simplify and create my own version of screencast key addon and this is my baby-stepping. What I'm doing here is to display a key on the screen that user pressed. However, the module msvcrt
causes Blender crashing.
Some people uses bge
or keyboard
modules for detecting pressed keys but somewhat reason I have no modules in my Python 3. So I decided using msvcrt
instead which is already exists on the module list.
I searched my problem on Google but sadly couldn't get an accepted solutions.
Any ideas?
This is the code:
bl_info = {
"name" : "KeyPad",
"author" : "anon",
"description" : "",
"blender" : (2, 80, 0),
"version" : (0, 0, 1),
"location" : "",
"warning" : "",
"category" : "Generic"
}
import bpy, blf, msvcrt
class Ksys:
defaults = {
"id": 0,
"handler": None,
"count": 3,
"color": [255, 255, 255],
"size": [50, 72],
"position": {
"left": [2, 80, 0],
"center": [],
"right": []
}
}
def __init__(self):
while True:
if msvcrt.kbhit():
key = msvcrt.getch()
print("Key Pressing detected!:", key)
Ksys.defaults["handler"] = bpy.types.SpaceView3D.draw_handler_add(self.draw(key), (None, None), 'WINDOW', 'POST_PIXEL')
print("Key Assigning detected!")
print("Waiting for 3 seconds then remove the handler on the window")
bpy.app.timers.register(self.remove(Ksys.defaults["handler"]), Ksys.defaults["count"])
def draw(key):
blf.size(Ksys.defaults["id"], Ksys.defaults["size"][0], Ksys.defaults["size"][1])
blf.color(Ksys.defaults["id"], Ksys.defaults["color"][0], Ksys.defaults["color"][1], Ksys.defaults["color"][2])
blf.draw(Ksys.defaults["id"], key)
def remove(key):
bpy.types.SpaceView3D.draw_handler_remove(key, 'WINDOW')
# test run before register
o = Ksys()
def register():
pass
def unregister():
pass
msvcrt
is the module that only avaliable on Windows (at least not one of default modules of Python I guess). So I'm currently using Windows. $\endgroup$msvcrt
is part of the Microsoft C++ runtime library and it's very much not recommended to use it raw, mostly because the code is not portable.bge
is a Blender module for the game engine, which was removed when the game engine was. This answer talks about doing kbd input with a modal operator. There are threads on how to do it with a separate blender thread but that's pretty hard to get right as Gorgious pointed out. $\endgroup$