python控制、監聽鼠標鍵盤

前言


python中控制、監聽鍵盤鼠標常用pynput模塊,有時也會使用pywin32模塊。

本文主要講如何使用pynput模塊控制、監聽鍵盤。由於本人能力有限,不足之處還望指正。

前期工作


①安裝pynput模塊。打開cmd,輸入pip install pynput即可。

②IDE的選擇。建議使用pycharm或spyder,因爲會自動補全代碼,很方便。

③亢奮的心情。學新知識前要儘量保持亢奮,如果你現在不是很亢奮,可以先去看幾個小電影。

注:安裝過程中如果速度很慢可是使用國內鏡像

打開cmd,輸入pip install 庫名 -i https://pypi.tuna.tsinghua.edu.cn/simple/

控制鍵盤


步驟

①實例化鍵盤對象

②模擬按壓、鬆開按鍵

③模擬按鍵分爲兩類:

​ 1、space、ctrl---------使用keyboard.press(Key.space)

​ 2、普通字母,a、b、A等----------使用keyboard.press(‘a’)

## ================================================
##              控制鍵盤
## ================================================
from pynput.keyboard import Key, Controller
keyboard = Controller()  #實例化鍵盤對象

# 按鍵盤和釋放鍵盤
keyboard.press(Key.space)  # 按下空格鍵
keyboard.release(Key.space)  # 鬆開空格鍵

# 按小寫的a
keyboard.press('a')
keyboard.release('a')

# 按住shift再按a
with keyboard.pressed(Key.shift):
    keyboard.press('a')
    keyboard.release('a')

# 直接輸入字符串
keyboard.type('Hello World')

注:當你不知道該按壓哪個鍵盤時可以先運行下面監聽鍵盤的函數,控制檯會自動顯示按鍵名稱。

如下圖:

易知我先按了空格鍵,後按了w鍵。只需要將輸出的內容放置到keyboard.press()括號內即可

監聽鍵盤


當鍵盤的有按鍵按下、松下會調用應綁定的函數

## ================================================
##              監聽鍵盤
## ================================================
from pynput.keyboard import Key, Listener
keyboard = Controller()  #實例化鍵盤對象

def on_press(key):  # 按鍵被按壓調用這個函數
    # 輸出按壓的按鍵名字
    print('{0} pressed'.format(key))

def on_release(key):  # 按鍵被鬆開調用這個函數
    # 輸出鬆開的按鍵名字
    print('{0} release'.format(key))
    if key == Key.esc:  # 如果按了Esc鍵就停止監聽
        return False  # Stop listener

# 連接事件以及釋放
with Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

控制鼠標


## ================================================
##              控制鼠標
## ================================================
from pynput.mouse import Button, Controller
mouse = Controller()  # 實例化對象

# 讀鼠標座標
print('The current pointer position is {0}'.format(mouse.position))

# 移動鼠標到指定位置
mouse.position = (10, 20)
print('Now we have moved it to {0}'.format(mouse.position))

# 移動鼠標到相對位置,以position爲原點
mouse.move(5, -5)

# 按住和放開鼠標
mouse.press(Button.left)
mouse.release(Button.left)

# 點擊鼠標左鍵2下
mouse.click(Button.left, 1)

# 滾動鼠標
mouse.scroll(0, 500)  # 0表示模式,500表示向上滑500,寫成-500則表示向下滑500

注:可以使用監聽鼠標的代碼獲取鼠標的實時位置

監聽鼠標


## ================================================
##              監聽鼠標
## ================================================
from pynput.mouse import Listener

def on_move(x, y):  # 監聽鼠標移動
    print('Pointer moved to {0}'.format((x, y)))

def on_click(x, y, button, pressed):  # 監聽鼠標點擊
    print('{0} at {1}'.format('Pressed' if pressed else 'Released', (x, y)))
    if not pressed:  # 如果沒有按壓就結束程序(即,單擊一下鼠標會結束程序)
        # Stop listener
        return False

def on_scroll(x, y, dx, dy):  # 監聽鼠標滾輪
    print('Scrolled {0}'.format((x, y)))

# 連接事件以及釋放
with Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
    listener.join()

pywin32模塊簡述


pywin32是比pynput更加基層的庫,也可以滿足以上需求。在此不做詳細介紹,有興趣同學可以百度一下。

pywin32庫按壓按鍵時使用虛擬鍵盤的方式,例如代碼中的0x53、0x11等,

具體按鍵的對應關係如下: 點擊這裏 下載

import win32api
import win32gui

# 按下ctrl+s
win32api.keybd_event(0x11, 0, 0, 0)  # 按下ctrl
win32api.keybd_event(0x53, 0, 0, 0)  # 按下s
win32api.keybd_event(0x53, 0, win32con.KEYEVENTF_KEYUP, 0)  # 鬆開s
win32api.keybd_event(0x11, 0, win32con.KEYEVENTF_KEYUP, 0)  # 鬆開ctrl

# 按下回車
win32api.keybd_event(0x0D, 0, 0, 0)  # 按下回車
win32api.keybd_event(0x0D, 0, win32con.KEYEVENTF_KEYUP, 0)  # 鬆開回車

#發送文字
hWndEdit="我愛阿龍"
win32gui.SendMessage(hWndEdit,win32con.WM_CHAR,x, 0)

控制鼠標鍵盤可以用來幹什麼?


簡易的消息轟炸機

注:先複製想輸出的話再啓動程序

pynput版本

print('Made by 帥帥龍')
from pynput.keyboard import Key, Controller
import time
keyboard = Controller()

a=input("請輸入你需要循環輸出的內容:")
b=eval(input('請輸入你想循環輸出的次數:'))
c=eval(input('逐字輸出請按1,整句輸出請按2:'))
print("數據已接收!請將光標移動到會話框")
time.sleep( 2 )
for i in range(3):
  print('距離程序運行還有%d秒!'%(3-i))
  time.sleep( 1 )
for i in range(b):#設置循環次數
  if c==2:
    keyboard.type(a)
    keyboard.press(Key.enter)
    keyboard.release(Key.enter)
    time.sleep(0.1)
  elif c==1:
    for t in a:
      keyboard.type(t)
      keyboard.press(Key.enter)
      keyboard.release(Key.enter)
      time.sleep(0.1)
  else:
    print('別亂輸啊...')
print('消息發送完成!請關閉窗口')

win32版本

print('Made by 帥帥龍')
import win32api
import win32con
import time
b=eval(input('請輸入你想循環輸出的次數:'))
a=eval(input('請輸入每條消息停留的間隙:'))
print("數據已接收!請將光標移動到會話框")
for i in range(3):
  print('距離程序運行還有%d秒!'%(3-i))
  time.sleep( 1 )

for i in range(b):#設置循環次數
  win32api.keybd_event(0x11,0,0,0)
  win32api.keybd_event(0x56,0,0,0)
  win32api.keybd_event(0x56,0,win32con.KEYEVENTF_KEYUP,0)
  win32api.keybd_event(0x11,0,win32con.KEYEVENTF_KEYUP,0)
  win32api.keybd_event(0x0D,0,0,0)
  win32api.keybd_event(0x0D,0,win32con.KEYEVENTF_KEYUP,0)
  time.sleep(a)
print('消息發送完成!請關閉窗口')

自己寫類selenium模塊


注:在這裏只給大家提供一個demo,有什麼問題可以私信我。

#coded by 帥帥龍
import time

def save_html(wait_time=2,save_wait_time=3,grade=1):  # 保存網頁
    from pynput.keyboard import Key, Controller
    keyboard = Controller()
    time.sleep(wait_time)  #等待響應時間
    keyboard.press(Key.ctrl_l)  # 按下ctrl
    keyboard.press("s")  # 按下s
    keyboard.release("s")  # 鬆開s
    keyboard.release(Key.ctrl_l)  # 鬆開ctrl
    time.sleep(save_wait_time)  # 等待彈出保存等待窗口的時間
    keyboard.press(Key.shift)
    keyboard.release(Key.shift)
    num=1
    if grade==1:
        path=r'C:\Users\86166\Desktop\存放網址\一級\序號:'+str(num)
        for i in path:
            keyboard.type(i)
    else:
        path = r'C:\Users\86166\Desktop\存放網址\二級\序號:' + str(num)
        for i in path:
            keyboard.type(i)
    num+=1
    keyboard.press(Key.enter)
    keyboard.release(Key.enter)


def type_url(url='www.baidu.com'):  # 輸入url
    from pynput.keyboard import Key, Controller
    keyboard = Controller()
    keyboard.press(Key.f6)
    keyboard.release(Key.f6)
    time.sleep(0.5)
    keyboard.press(Key.shift)
    keyboard.release(Key.shift)
    time.sleep(1)
    for i in url:
        keyboard.type(i)  # 輸入網站
    keyboard.press(Key.enter)  # 跳轉
    keyboard.release(Key.enter)


def scroll(end=-500,style=0):  # 滑動鼠標
    from pynput.mouse import Controller
    mouse=Controller()
    mouse.scroll(style, end)


def get_files_path(path='一級'):  # 獲取文件地址
    import os
    files=os.listdir(path)
    files_path=[path + i for i in files]
    return files_path


if __name__ == '__main__':
    time.sleep(3)
    type_url()
    save_html()

用代碼彈奏電子鋼琴


思路:

①下載everypiano或者easypiano模擬鋼琴軟件

②下載相應歌曲的epo文件,並看歌曲是怎麼彈奏的

③設置好時間間隔和按鍵順序,啓動程序

注:建議使用pywin32模塊

製作吃雞遊戲腳本


思路:

①訓練場使用槍支發射子彈,截圖並計時

②分析某時刻的彈道軌跡,並控制鼠標移動

③設置熱鍵,當按壓這個按鍵時調用②中的代碼,鬆開按鍵則停止射擊

③啓動程序後啓動遊戲

注:同理可以製作cf跳跳樂腳本

其他

略…

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章