python32模擬鼠標和鍵盤操做

前言
Windows pywin32容許你像vc同樣的形式來使用python開發win32應用。代碼風格能夠相似win32 sdk,也能夠相似MFC,由你選擇。若是你仍不放棄vc同樣的代碼過程在python下,這不錯的選擇。python

利用pywin32能夠自動化進行電腦操做。包括複製粘貼,鼠標移動,鍵盤輸入等等。api

下載連接函數

1、pywin32經常使用函數
(1)獲取鼠標位置
win32api.GetCursorPos()
1
(2)鼠標左鍵按下
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
1
(3)鼠標左鍵放開
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
1
(4)鼠標右鍵按下
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
1
(5)鼠標右鍵放開
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
1
(6)設置鼠標位置
win32api.SetCursorPos((x, y))
1
(7)鍵盤輸入事件
win32api.keybd_event(VK_CODE[word], 0, 0, 0)
win32api.keybd_event(VK_CODE[word], 0, win32con.KEYEVENTF_KEYUP, 0)
1
2
2、封裝接口
(1)獲取當前鼠標位置
def cursor_point(self):
"""
獲取當前鼠標位置
"""
pos = win32api.GetCursorPos()
return int(pos[0]), int(pos[1])
1
2
3
4
5
6
(2)鼠標左擊事件
def mouse_left_click(self, new_x=None, new_y=None, times=1):
"""
鼠標左擊事件
:param new_x: 新移動的座標x軸座標
:param new_y: 新移動的座標y軸座標1506240215
:param times: 點擊次數
"""
self.mouse_move(new_x, new_y)
time.sleep(0.05)
while times:
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
times -= 1
1
2
3
4
5
6
7
8
9
10
11
12
13
(3)鼠標右擊事件
def mouse_right_click(self, new_x=None, new_y=None):
"""
鼠標右擊事件
:param new_x: 新移動的座標x軸座標
:param new_y: 新移動的座標y軸座標
"""
self.mouse_move(new_x, new_y)
time.sleep(0.05)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
1
2
3
4
5
6
7
8
9
10
(4)移動鼠標位置
def mouse_move(self, new_x, new_y):
if new_y is not None and new_x is not None:
point = (new_x, new_y)
win32api.SetCursorPos(point)
self.x = new_x
self.y = new_y
1
2
3
4
5
6
(5)鍵盤輸入文本
def key_input(self, input_words=''):
for word in input_words:
win32api.keybd_event(VK_CODE[word], 0, 0, 0)
win32api.keybd_event(VK_CODE[word], 0, win32con.KEYEVENTF_KEYUP, 0)
time.sleep(0.1)
1
2
3
4
5
(6)鍵盤輸入事件
def key_even(self, input_key):
win32api.keybd_event(VK_CODE[input_key], 0, 0, 0)
win32api.keybd_event(VK_CODE[input_key], 0, win32con.KEYEVENTF_KEYUP, 0)
time.sleep(1)
1
2
3
4
3、代碼倉庫
---------------------
做者:畢宿
來源:CSDN
原文:https://blog.csdn.net/qq_33371343/article/details/78916751
版權聲明:本文爲博主原創文章,轉載請附上博文連接!.net

相關文章
相關標籤/搜索