使用win32 native api 来向窗口发送键盘消息,主要是为了做his程序的自动登陆脚本 来方面测试程序
把程序传上来留个笔记
set_foreground_window 根据标题来设定目标窗口
key_press 一次发送一个按键信息 包括key_down 和key_up
1 #coding=gbk
2 import win32gui,win32con,win32api,win32process
3 import string,os
4
5
6 __keys={ }
7 for key in dir(win32con):
8 if key.startswith('VK_'):
9 __keys[key[3:].capitalize()]=getattr(win32con,key)
10
11 def sleep(ms):
12 win32api.Sleep(ms)
13
14 def run(exe_file):
15
16 win32api.ShellExecute(0,"",exe_file,'','',0)
17
18 def set_foreground_window(win):
19 try:
20 win32gui.SetForegroundWindow(win)
21 win32api.Sleep(50)
22 except TypeError:
23 hwnd=win32gui.FindWindow(0,win)
24 win32gui.SetForegroundWindow(hwnd)
25 win32api.Sleep(50)
26 print hwnd
27
28 def dump_keys():
29 ks=[k for k in __keys.keys()]
30 ks.sort()
31 print "\n".join( "%s=0x%x"%(k,__keys[k]) for k in ks )
32
33 def keyboard_event(key,flag=0):
34 value=None
35 if isinstance (key,int):
36 value=key
37 else:
38 if len(key)==1:
39 value=win32api.VkKeyScan (key)
40 else:
41 key=key.capitalize()
42 if key in __keys:
43 value=__keys[key]
44
45 if value != None:
46 win32api.keybd_event(value,0,flag,0)
47 else:
48 raise TypeError()
49
50 def key_down(key):
51 keyboard_event(key)
52
53 def key_up(key):
54 keyboard_event(key,flag=win32con.KEYEVENTF_KEYUP)
55
56
57
58 def key_press(key):
59 if len(key)==1:
60 v=win32api.VkKeyScan (key)
61
62 c=v&0xff00
63
64 if c==1:
65 key_down('Shift')
66
67 key_down(v)
68 key_up(v)
69
70 if c==1:
71 key_up('Shift')
72 else:
73 key_down(key)
74 key_up(key)
75
76 if __name__=='__main__':
77 set_foreground_window('系统登录')
78
79 for i in '8888p':
80 key_press(i)
81 key_press('Return')
82
八月份发生了太多事情,技术上,工作上,生活上都有。本来可以写很多,想想还是算了, 太私人的东西不好意思放上来晒
posted on 2008-09-03 14:14
zarra 阅读(803)
评论(1) 编辑 收藏