我正在钻研C,因为我需要将ctypes库导入到python以允许键盘控制。我努力学习下面的代码是如何工作的:C - 签名和无符号整数
import ctypes
import time
SendInput = ctypes.windll.user32.SendInput
# C struct redefinitions
PUL = ctypes.POINTER(ctypes.c_ulong)
class KeyBdInput(ctypes.Structure):
_fields_ = [("wVk", ctypes.c_ushort),
("wScan", ctypes.c_ushort),
("dwFlags", ctypes.c_ulong),
("time", ctypes.c_ulong),
("dwExtraInfo", PUL)]
class HardwareInput(ctypes.Structure):
_fields_ = [("uMsg", ctypes.c_ulong),
("wParamL", ctypes.c_short),
("wParamH", ctypes.c_ushort)]
class MouseInput(ctypes.Structure):
_fields_ = [("dx", ctypes.c_long),
("dy", ctypes.c_long),
("mouseData", ctypes.c_ulong),
("dwFlags", ctypes.c_ulong),
("time",ctypes.c_ulong),
("dwExtraInfo", PUL)]
class Input_I(ctypes.Union):
_fields_ = [("ki", KeyBdInput),
("mi", MouseInput),
("hi", HardwareInput)]
class Input(ctypes.Structure):
_fields_ = [("type", ctypes.c_ulong),
("ii", Input_I)]
# Actuals Functions
def PressKey(hexKeyCode):
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput(hexKeyCode, 0x48, 0, 0, ctypes.pointer(extra))
x = Input(ctypes.c_ulong(1), ii_)
SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
def ReleaseKey(hexKeyCode):
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput(hexKeyCode, 0x48, 0x0002, 0, ctypes.pointer(extra))
x = Input(ctypes.c_ulong(1), ii_)
SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
def AltTab():
'''
Press Alt+Tab and hold Alt key for 2 seconds in order to see the overlay
'''
PressKey(0x012) #Alt
PressKey(0x09) #Tab
ReleaseKey(0x09) #~Tab
time.sleep(2)
ReleaseKey(0x012) #~Alt
if __name__ =="__main__":
AltTab()
我不理解有关符号和无符号整数部分:
INT射程为-32768 - 32767
unsigned int的取值范围为0 - 65535
我读到:“由于您有16位可以表示数字,所以可以用2字节数显示的数字的总范围是2^16^2^16与65536相同,因为我们从0开始计数,与0 - 65535相同。这显然与一个unsigned int值相匹配,所以你可以看到,这是多么这种类型的操作“
这似乎是有道理的,但有一件事我不明白:
1字节= 8位 2个字节= 16位
那么为什么2字节数被称为2^16而不是2^8?
,因为它有16位。每个位可以容纳2个值,因此2^16个可能的数字与2个字节 – pippin1289
啊当然,谢谢。 – Phoenix
注意:根据C,[byte](http://en.wikipedia.org/wiki/Byte#Common_uses)至少为8位。 – chux