国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

pywin32庫 : Python 操作 windows 系統(tǒng) API

這篇具有很好參考價值的文章主要介紹了pywin32庫 : Python 操作 windows 系統(tǒng) API。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

Python 模塊雖多,但也不可能滿足所有需求。而且,模塊為了便于使用,通常都封裝過度,有些功能無法靈活使用,必須直接調(diào)用Windows API 來實現(xiàn)。要完成這一目標,有兩種辦法,一種是使用 C 編寫 Python 擴展模塊,另一種就是編寫普通的 DLL 通過 python 的 ctypes 來調(diào)用。

Python 沒有自帶訪問 windows 系統(tǒng) API 的庫的,需要下載 pywin32,pywin32 是一個第三方模塊庫,主要的作用是方便 python 開發(fā)者快速調(diào)用 windows API 的一個模塊庫。它直接包裝了幾乎所有的 Windows API,可以方便地從 Python 直接調(diào)用,該模塊另一大主要功能是通過 Python 進行 COM 編程。

Python extensions for Microsoft Windows Provides access to much of the Win32 API, the ability to create and use COM objects, and the Pythonwin environment.
翻譯過來就是:pywin32 是 針對 Microsoft Windows 的 Python擴展,提供了對大部分 Win32 API 的訪問、創(chuàng)建、和使用 COM對象 的能力以及 Pythonwin 環(huán)境。

pywin32 提供了齊全的windows 常量、接口、線程 以及 COM機制 等等。Windows Pywin32 允許你像 VC 一樣的形式來使用PYTHON開發(fā) win32 應(yīng)用。代碼風格可以類似 win32 sdk,也可以類似MFC,由你選擇。如果你仍不放棄vc一樣的代碼過程在python下,那么這就是一個不錯的選擇。

1、window 消息、句柄

為了查找目標窗口的句柄,可以下載一個微軟自家的 Spy++,可以很方便的查看窗體的消息。

深入理解 windows 消息機制:https://blog.csdn.net/liulianglin/article/details/14449577
Microsoft Win32 程序員參考 (在線 API):http://www.yfvb.com/help/win32sdk/index.htm

  • 句柄:是一個 32 位整數(shù),在 windows 中標記對象用,類似一個 dict 中的 key。在 win32 編程的世界里,包括 "窗口、文本框所有控件" 都是 窗體,所有的窗體都有獨立的句柄。要操作任意一個窗體,你都需要找到這個窗體的句柄?。窗口句柄(具體位數(shù)跟個人PC操作系統(tǒng)位數(shù)相關(guān)),它表示的是消息所屬的窗口。我們通常開發(fā)的程序都是窗口應(yīng)用程序,一般一個消息都是和某個窗口相關(guān)聯(lián)的。比如我們在某個活動窗口按下鼠標右鍵,此時產(chǎn)生的消息就是發(fā)送給該活動窗口的。窗口可以是任何類型的屏幕對象,因為Win32能夠維護大多數(shù)可視對象的句柄(窗口、對話框、按鈕、編輯框等)。補充一下:“句柄”---在Windows程序中,有各種各樣的資源,系統(tǒng)在創(chuàng)建這些資源的時候,都會為他們分配內(nèi)存,并返回標識這些資源的標識號,這個標識號就是句柄)。
  • 消息:即 消息的標識符,是一些常量值,這些常量可以是Windows單元中預定義的常量,也可以是自定義的常量。在 Windows 中消息是由一個數(shù)值表示的,不同的消息對應(yīng)不同的數(shù)值。 消息 是 windows 應(yīng)用的重要部分,用來告訴窗體 "發(fā)生了什么",比如 給一個按鈕發(fā)送BN_CLICKED 這么個消息,按鈕就知道 "哦,我被點了",才能執(zhí)行相應(yīng)的下一步操作。但是當這些消息種類多到足以挑戰(zhàn)我們的 IQ 時,所以聰明的程序開發(fā)者便想到將這些數(shù)值定義為WM_XXX 宏的形式。例如,鼠標左鍵按下的消息--WM_LBUTTONDOWN,鍵盤按下消息--WM_KEYDOWN,字符消息--WM_CHAR,等等。消息標識符以常量命名的方式指出消息的含義。當窗口過程接收到消息之后,他就會使用消息標識符來決定如何處理消息。例如、WM_PAINT告訴窗口過程窗體客戶區(qū)被改變了需要重繪。符號常量指定系統(tǒng)消息屬于的類別,其前綴指明了處理解釋消息的窗體的類型。
  • wParam 和 lParam:用于指定消息的附加信息。例如,當我們收到一個鍵盤按下消息的時候,message 成員變量的值就是 WM_KEYDOWN,但是用戶到底按下的是哪一個按鍵,我們就得拜托這二位,由他們來告知我們具體的信息。
  • ?time 和 pt:這倆個變量分別被用來表示消息投遞到消息隊列中的時間和鼠標當前的位置,一般情況下不怎么使用(但不代表沒用)

PyWin32 地址:https://github.com/mhammond/pywin32
PyWin32 文檔:http://timgolden.me.uk/pywin32-docs/contents.html

2、安裝?pywin32

安裝:pip install pywin32

  • win32api :模塊內(nèi)定義了常用的一些 API函數(shù),例如:MessageBox
  • win32gui :模塊內(nèi)定義了一些有關(guān) 圖形操作的API,例如:FindWindow
  • win32con :模塊內(nèi)定義了 windows API 內(nèi)的宏,即?宏常量。例如 MessageBox 內(nèi)的 MB_OK。(?ps:con 個人理解 是 const 常量 的意思 )

安裝完成后,在 Python 安裝路徑下?

  • Lib\site-packages\win32 下是所有的 API 支撐模塊。pywin32庫 : Python 操作 windows 系統(tǒng) API
  • Lib\site-packages\win32com 下是 COM 的支撐模塊。pywin32庫 : Python 操作 windows 系統(tǒng) API

在 Lib\site-packages 下有一個 PyWin32.CHM 幫助文件,對 Windows 編程有一定基礎(chǔ)的看了這個幫助文件就能很快上手。pywin32 把 Windows API 按照功能分了一些大類,每一個大類作為一個模塊。以下是所有的模塊:

  • mmapfile:提供對內(nèi)存映射文件 API 的訪問
  • odbc:odb 數(shù)據(jù)庫 api
  • perfmon:包裝性能監(jiān)視器功能的模塊。
  • pywintypes:支持常見 Windows 類型的模塊。
  • servicemanager:與 Windows 服務(wù)控制管理器交互的模塊。
  • timer:包裝 Win32 Timer 函數(shù)的擴展
  • win2kras:將 Windows 2000 擴展封裝到遠程訪問服務(wù) (RAS) API 的模塊。
  • win32api提供了常用的用戶API
  • win32clipboard:提供了有關(guān)粘貼板的API
  • win32con有關(guān)的常量。提供了消息常量的操作API。
  • win32console:控制臺
  • win32cred:憑證管理功能的接口。此模塊中的功能僅適用于 Windows XP 及更高版本。
  • win32crypt:win32 Cryptography API 的接口
  • win32event:提供 win32 事件/等待API接口
  • win32evtlog:封裝了 Windows Win32 事件日志 API。
  • win32file提供了有關(guān)文件操作的API
  • win32gui提供了有關(guān) windows 用戶界面圖形操作的API
  • win32help:Win32 API 的幫助
  • win32inet:Windows internet (wininet) API 接口
  • win32job:win32 進程和線程 API 的接口,在 Windows 2000 及更高版本中可用。
  • win32lz:封裝 Windows LZ 壓縮例程的模塊
  • win32net:Windows 網(wǎng)絡(luò)API的模塊
  • win32pdh:封裝 Windows 性能數(shù)據(jù)幫助 API?模塊
  • win32pipe:管道 api
  • win32print:Windows 打印 API 的模塊
  • win32process進程 api
  • win32profile:包裝用于處理用戶配置文件的函數(shù)
  • win32ras:封裝 Windows Remote Access Service (RAS) API
  • win32security:win32 安全 API 接口
  • win32service:服務(wù)
  • win32trace
  • win32transaction:內(nèi)核事務(wù)管理器函數(shù) 模塊,用于事務(wù)NTFS和事務(wù)注冊表函數(shù)。
  • win32ts:此模塊中的所有函數(shù)都接受關(guān)鍵字參數(shù)
  • win32wnet:公開 Windows Networking API 的模塊。
  • winxpgui:xp 圖像用戶界面 API

比如 文件類 API 就在模塊 win32file 中,進程類 API 在模塊 win32process 中。在使用的時候,按需導入相關(guān)模塊就行了,win32con 則定義了所有的常量,幾乎是必不可少的,一些難以分類的 API 則在模塊 win32api 中(大部分是kernel32.dll導出的API)。

部分模塊之間還存在一些交叉,比如 CreateFile 的參數(shù)中用到的 GENERIC_READ 常量,在 win32con 中有定義,在 win32file 中也有定義。用戶只要大概知道這個是文件 API 用到的常量,那么不管你寫 win32file.GENERIC_READ還是 win32con.GENERIC_READ 都是可以的。關(guān)閉句柄用的 CloseHandle 函數(shù)也是在兩個模塊中都有定義的。需要注意的是,微軟提供的 Wsa 系列網(wǎng)絡(luò) API 也都在 win32file 模塊中,因為很多操作系統(tǒng)都是把套接字也用為文件對象來操作的。

如果不清楚要使用的 API 在哪個模塊中,到 幫助文件 里搜索一下就可以得到答案。

pywin32庫 : Python 操作 windows 系統(tǒng) API

如果對 pywin32 中如何調(diào)用某個 API 不熟悉,那么查看 Pywin32.CHM 就足夠了,如果對 API 本身的參數(shù)定義和使用不熟悉,那還得繼續(xù)看 MSDN。

3、使用 pywin32 編寫 windows 的 GUI

《python 寶典》:https://wenku.baidu.com/view/1f4eb95df011f18583d049649b6648d7c0c70830.html

示例:Helloworld:

pywin32庫 : Python 操作 windows 系統(tǒng) API

示例:創(chuàng)建文件

在 Lib\site-packages\win32\Demos 目錄下有很多例子,如果不清楚 pywin32 怎么用,可以看這些例子,比如 使用 API 進行文件操作:

# This is a "demo" of win32file - it used to be more a test case than a
# demo, so has been moved to the test directory.
# Please contribute your favourite simple little demo.
import win32file, win32api, win32con
import os


# A very simple demo - note that this does no more than you can do with
# builtin Python file objects, so for something as simple as this, you
# generally *should* use builtin Python objects.  Only use win32file etc
# when you need win32 specific features not available in Python.

def SimpleFileDemo():
    testName = os.path.join(win32api.GetTempPath(), "win32file_demo_test_file")
    if os.path.exists(testName): os.unlink(testName)
    # Open the file for writing.
    handle = win32file.CreateFile(
        testName,
        win32file.GENERIC_WRITE,
        0,
        None,
        win32con.CREATE_NEW,
        0,
        None
    )
    test_data = "Hello\0there".encode("ascii")
    win32file.WriteFile(handle, test_data)
    handle.Close()
    # Open it for reading.
    handle = win32file.CreateFile(testName, win32file.GENERIC_READ, 0, None, win32con.OPEN_EXISTING, 0, None)
    rc, data = win32file.ReadFile(handle, 1024)
    handle.Close()  # 此處也可使用win32file.CloseHandle(handle)來關(guān)閉句柄
    if data == test_data:
        print("Successfully wrote and read a file")
    else:
        raise Exception("Got different data back???")
    os.unlink(testName)


if __name__ == '__main__':
    SimpleFileDemo()

點擊 鼠標

win32gui? 和 win32ui :從字面意思來看,一個是 gui(圖形用戶接口),一個是 ui (用戶接口),但是看不出有什么區(qū)別,查看源碼也沒發(fā)現(xiàn)有什么說明。

pywin32庫 : Python 操作 windows 系統(tǒng) API

?示例:

import win32gui, win32api, win32con
# 獲取鼠標當前位置的坐標
win32api.GetCursorPos()
# 將鼠標移動到坐標處
win32api.SetCursorPos((200, 200))
# 左點擊
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 200, 200, 0, 0)
win32api.mouse_event(win32con.MUOSEEVENTF_LEFTUP, 200, 200, 0, 0)
# 獲取窗口句柄
win32gui.FindWindow(None, 'qq')
win32gui.FindWindow('TXGuiFoundation', None)
# 通過坐標獲取窗口句柄
hw = win32api.WindowFromPoint(win32api.GetCursorPos())
# 獲取窗口classname
win32gui.GetClassName(hw)
# 獲取窗口標題
win32gui.GetWindowText(hw)
# 獲取窗口坐標
win32gui.GetwindowRect(hw)

通過窗口標題獲取句柄

import win32gui
 
hld = win32gui.FindWindow(None,u"Adobe Acrobat") #返回窗口標題為Adobe Acrobat的句柄

通過父窗口句柄獲取子句柄

#parent為父窗口句柄id
def get_child_windows(parent):
    '''
    獲得parent的所有子窗口句柄
     返回子窗口句柄列表
     '''
    if not parent:
        return
    hwndChildList = []
    win32gui.EnumChildWindows(parent, lambda hwnd, param: param.append(hwnd),  hwndChildList)
    return hwndChildList

根據(jù)句柄獲取句柄標題和類名

import win32gui
 
title = win32gui.GetWindowText(jbid)   #jbid為句柄id
#獲取標題
clsname = win32gui.GetClassName(jbid)  
#獲取類名

根據(jù)句柄獲取窗口位置

import win32gui
left, top, right, bottom = win32gui.GetWindowRect(jbid)
#分別為左、上、右、下的窗口位置

根據(jù)句柄進行點擊操作

import win32api,win32con
 
win32api.SetCursorPos([橫坐標, 縱坐標])
#根據(jù)橫縱坐標定位光標
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP | win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
#給光標定位的位置進行單擊操作(若想進行雙擊操作,可以延時幾毫秒再點擊一次)
win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTUP | win32con.MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0)
#給光標定位的位置進行右擊操作

根據(jù)句柄將窗口放在最前

win32gui.SetForegroundWindow(jbid)

查找窗體句柄

在 win32 編程的世界里,包括 "窗口、文本框所有控件" 都是 窗體,所有的窗體都有獨立的句柄。要操作任意一個窗體,你都需要找到這個窗體的句柄,這里,可以用到 FindWindow函數(shù)和FindWindowEx函數(shù)。在 pywin32 中,他們都屬于 win32gui 的模塊。

FindWindow(lpClassName=None, lpWindowName=None):

描述:自頂層窗口(也就是桌面)開始搜索條件匹配的窗體,并返回這個窗體的句柄。不搜索子窗口、不區(qū)分大小寫。找不到就返回0?
參數(shù):?
lpClassName:字符型,是窗體的類名,這個可以在Spy++里找到。?
lpWindowName:字符型,是窗口名,也就是標題欄上你能看見的那個標題。?
說明:這個函數(shù)我們僅能用來找主窗口。

示例代碼 1 (獲取所有窗口句柄。使用 win32gui 模塊) :

import win32gui


titles = set()


def foo(hwnd, mouse):
    # 去掉下面這句就所有都輸出了,但是我不需要那么多
    if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
        titles.add(win32gui.GetWindowText(hwnd))


def test():
    win32gui.EnumWindows(foo, 0)
    lt = [t for t in titles if t]
    lt.sort()
    for t in lt:
        print(t)


if __name__ == '__main__':
    test()
import win32gui

hwnd_title = dict()


def get_all_hwnd(hwnd, mouse):
    if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
        hwnd_title.update({hwnd: win32gui.GetWindowText(hwnd)})


win32gui.EnumWindows(get_all_hwnd, 0)

for h, t in hwnd_title.items():
    if t is not "":
        print(h, t)

示例代碼 2 :( 使用 win32ui 模塊)

import win32ui


def test():
    dlg = win32ui.CreateFileDialog(1)  # 1表示打開文件對話框
    dlg.SetOFNInitialDir('E:/Python')  # 設(shè)置打開文件對話框中的初始顯示目錄
    dlg.DoModal()

    filename = dlg.GetPathName()  # 獲取選擇的文件名稱
    print(filename)


if __name__ == '__main__':
    test()

示例代碼 3:

import win32api
import win32con
import win32gui
import win32ui
import win32console
import win32process
import os
import signal

MAIN_HWND = 0


def is_win_ok(hwnd, starttext):
    s = win32gui.GetWindowText(hwnd)
    if starttext in s:
        print(s)
        global MAIN_HWND
        MAIN_HWND = hwnd
        return None
    return 1


def find_main_window(starttxt):
    global MAIN_HWND
    win32gui.EnumChildWindows(0, is_win_ok, starttxt)
    return MAIN_HWND


def winfun(hwnd, lparam):
    s = win32gui.GetWindowText(hwnd)
    if len(s) > 3:
        print("winfun, child_hwnd: %d txt: %s" % (hwnd, s))
    return 1


if __name__ == '__main__':

    os.system('start cmd')
    window_title = 'C:\Windows\system32\cmd.exe'
    window_handle = win32gui.FindWindow(None, window_title)
    window_handle_title = win32gui.GetWindowText(window_handle)
    window_handle_class_name = win32gui.GetClassName(window_handle)

    print(window_handle_title)
    print(window_handle_class_name)
    win32gui.CloseWindow(window_handle)  # 窗口最小化
    win32gui.SendMessage(window_handle, win32con.WM_CLOSE)  # 關(guān)閉窗口
    # win32api.SetCursorPos([0, 0])  # 設(shè)置 鼠標 位置

    file_path = './test.txt'
    with open(file_path, 'w+') as f:
        pass
    os.system('start {0}'.format(file_path))

    main_app = 'test.txt - 記事本'
    hwnd = win32gui.FindWindow(None, main_app)
    win32gui.CloseWindow(hwnd)  # 窗口最小化
    print(win32gui.GetWindowText(hwnd))
    print(type(hwnd))
    print(hwnd)
    if hwnd < 1:
        hwnd = find_main_window(main_app)
    print(type(hwnd))
    print(hwnd)
    if hwnd:
        win32gui.EnumChildWindows(hwnd, winfun, None)

    thread, processId = win32process.GetWindowThreadProcessId(hwnd)
    print(thread)
    # print(processId, signal.CTRL_BREAK_EVENT)
    # os.kill(processId, signal.CTRL_C_EVENT)
    # os.kill(processId, signal.CTRL_BREAK_EVENT)

    # Shows or hides a window and changes its state
    win32gui.ShowWindow(hwnd, 0)
    # win32gui.HideCaret(hwnd)

示例代碼 4:

import win32gui
import win32con
import win32api
import win32process
import os


spider_config_count = dict(
    mao_yan_spider=10,
    tao_piao_piao_spider=10,
)


# 保存 句柄 和 句柄 title。 示例 { 100 : 'C:\Windows\system32\cmd.exe'}
handle_title_dict = dict()

# 通過 spider_config_count 生成 keyword_list。
keyword_list = list()

# 每個 spider 對應(yīng)的數(shù)量
spider_count_dict = dict()

# 所有 進程 對應(yīng)的數(shù)量
process_count_dict = dict()


for temp_k, temp_v in spider_config_count.items():
    keyword_list.append(temp_k)


def get_windows_handle(hwnd, mouse):
    if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
        handle_title_dict.update({hwnd: win32gui.GetWindowText(hwnd)})


def get_all_windows_handle():
    win32gui.EnumWindows(get_windows_handle, 0)
    for k, v in handle_title_dict.items():
        # print('{0} : {1}'.format(k, v))
        pass


def close_process():
    # for k, v in WINDOWS_HANDLE_DICT.items():
    #     # print('{0} : {1}'.format(k, v))
    #     if WINDOWS_HANDLE_DICT[k] in WINDOWS_HANDLE_TITLE_LIST:
    #         print('{0} : {1}'.format(k, v))
    pass


def display_all_spider_count():
    for k, v in handle_title_dict.items():
        if handle_title_dict[k]:
            for keyword in keyword_list:
                if keyword in v:
                    if not spider_count_dict.get(keyword):
                        spider_count_dict[keyword] = 1
                    else:
                        spider_count_dict[keyword] += 1

    for k, v in spider_count_dict.items():
        print('{0} : {1}'.format(k, v))


def display_all_process_count():
    for k, v in handle_title_dict.items():
        if handle_title_dict[k]:
            if not process_count_dict.get(v):
                process_count_dict[v] = 1
            else:
                process_count_dict[v] += 1
    for k, v in process_count_dict.items():
        print('{0} : {1}'.format(k, v))
    pass


def monitoring_spider_count():
    pan = 'E:'
    # spider_path = 'PythonSpider/maoyan'
    spider_path = 'PythonSpider/taopiaopiaoSpider'

    for k, v in spider_config_count.items():
        # for k_2, v_2 in spider_count_dict:
        if spider_count_dict.get(k):
            if spider_count_dict[k] < v:

                count = v - spider_count_dict[k]
                # win_cmd = 'for /L %i in (1,1,5) do start cmd /k "e: && cd PythonSpider" '
                win_cmd = 'for /L %i in (1,1,{0}) do start cmd /k "{1} && cd {2} && scrapy crawl {3}"'.format(
                    count, pan, spider_path, k
                )
                os.system(win_cmd)
        else:
            count = v
            win_cmd = 'for /L %i in (1,1,{0}) do start cmd /k "{1} && cd {2} && scrapy crawl {3}"'.format(
                count, pan, spider_path, k
            )
            os.system(win_cmd)
    pass


def test():
    get_all_windows_handle()
    for k, v in handle_title_dict.items():
        # print('{0} : {1}'.format(k, v))
        if handle_title_dict[k] == '無標題 - 記事本':
            print('{0} : {1}'.format(k, v))

            # 如果記事本有 內(nèi)容未保存,win32gui.SendMessage(k, win32con.WM_CLOSE) 這個無法關(guān)閉
            # win32gui.SendMessage(k, win32con.WM_CLOSE)

            # 終止進程 方式  可以關(guān)閉記事本中有內(nèi)容未保存
            thread_id, process_id = win32process.GetWindowThreadProcessId(k)
            p_handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, 0, process_id)
            win32api.TerminateProcess(p_handle, process_id)
            win32api.CloseHandle(p_handle)


get_all_windows_handle()


def test_2():
    win_cmd = 'for /L %i in (1,1,5) do start cmd /k "e: && cd PythonSpider" '
    os.system(win_cmd)


if __name__ == '__main__':
    # display_all_spider_count()
    display_all_process_count()
    # monitoring_spider_count()
    pass

窗口句柄 發(fā)送消息 常用方法 鍵盤輸入

python win32api win32gui win32con

推薦微軟的 Spy++ (下載地址:https://download.csdn.net/download/freeking101/11002997)來查看窗口類名等信息。

# -*- coding:utf-8 -*-

import time
import win32gui
import win32con
import win32api

# 從頂層窗口向下搜索主窗口,無法搜索子窗口
# FindWindow(lpClassName=None, lpWindowName=None)  窗口類名 窗口標題名
handle = win32gui.FindWindow("Notepad", None)

# 獲取窗口位置
left, top, right, bottom = win32gui.GetWindowRect(handle)
# 獲取某個句柄的類名和標題
title = win32gui.GetWindowText(handle)
cls_name = win32gui.GetClassName(handle)

# 打印句柄
print(handle)
print(cls_name)

# 搜索子窗口
# 枚舉子窗口
hwndChildList = []
win32gui.EnumChildWindows(handle, lambda hwnd, param: param.append(hwnd), hwndChildList)

# 父窗口句柄 若不為0,則按照z-index的順序從hwndChildAfter向后開始搜索子窗體,否則從第一個子窗體開始搜索。 子窗口類名 子窗口標題
# FindWindowEx(hwndParent=0, hwndChildAfter=0, lpszClass=None, lpszWindow=None)
subHandle = win32gui.FindWindowEx(handle, 0, "EDIT", None)

# 獲得窗口的菜單句柄
menuHandle = win32gui.GetMenu(subHandle)
# 獲得子菜單或下拉菜單句柄
# 參數(shù):菜單句柄 子菜單索引號
subMenuHandle = win32gui.GetSubMenu(menuHandle, 0)
# 獲得菜單項中的的標志符,注意,分隔符是被編入索引的
# 參數(shù):子菜單句柄 項目索引號
menuItemHandle = win32gui.GetMenuItemID(subMenuHandle, 0)
# 發(fā)送消息,加入消息隊列,無返回
# 參數(shù):句柄 消息類型 WParam IParam
win32gui.postMessage(subHandle, win32con.WM_COMMAND, menuItemHandle, 0)

# wParam的定義是32位整型,high word就是他的31至16位,low word是它的15至0位。
# 當參數(shù)超過兩個,wParam和lParam不夠用時,可以將wParam就給拆成兩個int16來使用。
# 這種時候在python里記得用把HIWORD的常數(shù)向左移16位,再加LOWORD,即wParam = HIWORD<<16+LOWORD。

# 下選框內(nèi)容更改
# 參數(shù):下選框句柄; 消息內(nèi)容; 參數(shù)下選框的哪一個item,以0起始的待選選項的索引;如果該值為-1,將從組合框列表中刪除當前選項,并使當前選項為空; 參數(shù)
# CB_Handle為下選框句柄,PCB_handle下選框父窗口句柄
if win32api.SendMessage(CB_handle, win32con.CB_SETCURSEL, 1, 0) == 1:
    # 下選框的父窗口命令
    # 參數(shù):父窗口句柄; 命令; 參數(shù):WParam:高位表示類型,低位表示內(nèi)容;參數(shù)IParam,下選框句柄
    # CBN_SELENDOK當用戶選擇了有效的列表項時發(fā)送,提示父窗體處理用戶的選擇。 LOWORD為組合框的ID. HIWORD為CBN_SELENDOK的值。
    win32api.SendMessage(PCB_handle, win32con.WM_COMMAND, 0x90000, CB_handle)
    # CBN_SELCHANGE當用戶更改了列表項的選擇時發(fā)送,不論用戶是通過鼠標選擇或是通過方向鍵選擇都會發(fā)送此通知。LOWORD為組合框的ID. HIWORD為CBN_SELCHANGE的值。
    win32api.SendMessage(PCB_handle, win32con.WM_COMMAND, 0x10000, CB_handle)

# 設(shè)置文本框內(nèi)容,等窗口處理完畢后返回true。中文需編碼成gbk
# 參數(shù):句柄;消息類型;參數(shù)WParam,無需使用; 參數(shù)IParam,要設(shè)置的內(nèi)容,字符串
win32api.SendMessage(handle, win32con.WM_SETTEXT, 0, os.path.abspath(fgFilePath).encode('gbk'))

# 控件點擊確定,處理消息后返回0
# 參數(shù):窗口句柄; 消息類型; 參數(shù)WParam HIWORD為0(未使用),LOWORD為控件的ID; 參數(shù)IParam  0(未使用),確定控件的句柄
win32api.SendMessage(Mhandle, win32con.WM_COMMAND, 1, confirmBTN_handle)

# 獲取窗口文本不含截尾空字符的長度
# 參數(shù):窗口句柄; 消息類型; 參數(shù)WParam; 參數(shù)IParam
bufSize = win32api.SendMessage(subHandle, win32con.WM_GETTEXTLENGTH, 0, 0) + 1
# 利用api生成Buffer
strBuf = win32gui.PyMakeBuffer(bufSize)
print(strBuf)
# 發(fā)送消息獲取文本內(nèi)容
# 參數(shù):窗口句柄; 消息類型;文本大??; 存儲位置
length = win32gui.SendMessage(subHandle, win32con.WM_GETTEXT, bufSize, strBuf)
# 反向內(nèi)容,轉(zhuǎn)為字符串
# text = str(strBuf[:-1])

address, length = win32gui.PyGetBufferAddressAndLen(strBuf)
text = win32gui.PyGetString(address, length)
# print('text: ', text)

# 鼠標單擊事件
# 鼠標定位到(30,50)
win32api.SetCursorPos([30, 150])
# 執(zhí)行左單鍵擊,若需要雙擊則延時幾毫秒再點擊一次即可
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP | win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
# 右鍵單擊
win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTUP | win32con.MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0)


def click1(x, y):  # 第一種
    win32api.SetCursorPos((x, y))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)


def click2(x, y):  # 第二種
    ctypes.windll.user32.SetCursorPos(x, y)
    ctypes.windll.user32.mouse_event(2, 0, 0, 0, 0)
    ctypes.windll.user32.mouse_event(4, 0, 0, 0, 0)


def click_it(pos):  # 第三種
    handle = win32gui.WindowFromPoint(pos)
    client_pos = win32gui.ScreenToClient(handle, pos)
    tmp = win32api.MAKELONG(client_pos[0], client_pos[1])
    win32gui.SendMessage(handle, win32con.WM_ACTIVATE, win32con.WA_ACTIVE, 0)
    win32gui.SendMessage(handle, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, tmp)
    win32gui.SendMessage(handle, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, tmp)


# 發(fā)送回車
win32api.keybd_event(13, 0, 0, 0)
win32api.keybd_event(13, 0, win32con.KEYEVENTF_KEYUP, 0)

# 關(guān)閉窗口
win32gui.PostMessage(win32lib.findWindow(classname, titlename), win32con.WM_CLOSE, 0, 0)

# 檢查窗口是否最小化,如果是最大化
if win32gui.IsIconic(hwnd):
    # win32gui.ShowWindow(hwnd, win32con.SW_SHOWNORMAL)
    win32gui.ShowWindow(hwnd, 8)
    time.sleep(0.5)

# SW_HIDE:隱藏窗口并激活其他窗口。nCmdShow=0。
# SW_MAXIMIZE:最大化指定的窗口。nCmdShow=3。
# SW_MINIMIZE:最小化指定的窗口并且激活在Z序中的下一個頂層窗口。nCmdShow=6。
# SW_RESTORE:激活并顯示窗口。如果窗口最小化或最大化,則系統(tǒng)將窗口恢復到原來的尺寸和位置。在恢復最小化窗口時,應(yīng)用程序應(yīng)該指定這個標志。nCmdShow=9。
# SW_SHOW:在窗口原來的位置以原來的尺寸激活和顯示窗口。nCmdShow=5。
# SW_SHOWDEFAULT:依據(jù)在STARTUPINFO結(jié)構(gòu)中指定的SW_FLAG標志設(shè)定顯示狀態(tài),STARTUPINFO 結(jié)構(gòu)是由啟動應(yīng)用程序的程序傳遞給CreateProcess函數(shù)的。nCmdShow=10。
# SW_SHOWMAXIMIZED:激活窗口并將其最大化。nCmdShow=3。
# SW_SHOWMINIMIZED:激活窗口并將其最小化。nCmdShow=2。
# SW_SHOWMINNOACTIVE:窗口最小化,激活窗口仍然維持激活狀態(tài)。nCmdShow=7。
# SW_SHOWNA:以窗口原來的狀態(tài)顯示窗口。激活窗口仍然維持激活狀態(tài)。nCmdShow=8。
# SW_SHOWNOACTIVATE:以窗口最近一次的大小和狀態(tài)顯示窗口。激活窗口仍然維持激活狀態(tài)。nCmdShow=4。
# SW_SHOWNORMAL:激活并顯示一個窗口。如果窗口被最小化或最大化,系統(tǒng)將其恢復到原來的尺寸和大小。應(yīng)用程序在第一次顯示窗口的時候應(yīng)該指定此標志。nCmdShow=1。

win32 雖然也可控制鍵盤,但不如使用 PyUserInput 的方便。需要注意在 windows 和 mac 下接口參數(shù)可能有所不同

# win32雖然也可控制鍵盤,但不如使用PyUserInput的方便。
# 需要注意在windows和mac下接口參數(shù)可能有所不同。
from pymouse import PyMouse
from pykeyboard import PyKeyboard
m = PyMouse()
k = PyKeyboard()

x_dim, y_dim = m.screen_size()
# 鼠標點擊
m.click(x_dim/2, y_dim/2, 1)
# 鍵盤輸入
k.type_string('Hello, World!')

# 按住一個鍵
k.press_key('H')
# 松開一個鍵
k.release_key('H')
# 按住并松開,tap一個鍵
k.tap_key('e')
# tap支持重復的間歇點擊鍵
k.tap_key('l',n=2,interval=5) 
# 發(fā)送判斷文字
k.type_string('123456')

#創(chuàng)建組合鍵
k.press_key(k.alt_key)
k.tap_key(k.tab_key)
k.release_key(k.alt_key)
# 特殊功能鍵
k.tap_key(k.function_keys[5]) # Tap F5
k.tap_key(k.numpad_keys['Home']) # Tap 'Home' on the numpad
k.tap_key(k.numpad_keys[5], n=3) # Tap 5 on the numpad, thrice

# Mac系統(tǒng)
k.press_keys(['Command','shift','3'])
# Windows系統(tǒng)
k.press_keys([k.windows_l_key,'d'])

# 其中的 PyMouseEvent 和 PyKeyboardEvent 還可用于監(jiān)聽鼠標和鍵盤事件的輸入

Python?鼠標、鍵盤

pynput 文檔:https://pythonhosted.org/pynput/index.html

安裝:pip?install?pynput

pynput 這個庫讓你可以控制和監(jiān)控輸入設(shè)備。

對于每一種輸入設(shè)備,它包含一個子包來控制和監(jiān)控該種輸入設(shè)備:

  • pynput.mouse:包含控制和監(jiān)控鼠標或者觸摸板的類。
  • pynput.keyboard:包含控制和監(jiān)控鍵盤的類。

地址:https://pypi.python.org/pypi/pynput

基本用法介紹:

from pynput.mouse import Button, Controller
import time

mouse = Controller()
print(mouse.position)
time.sleep(3)
print('The current pointer position is {0}'.format(mouse.position))

# set pointer positon
mouse.position = (277, 645)
print('now we have moved it to {0}'.format(mouse.position))

# 鼠標移動(x,y)個距離
mouse.move(5, -5)
print(mouse.position)

mouse.press(Button.left)
mouse.release(Button.left)

# Double click
mouse.click(Button.left, 1)

# scroll two steps down
mouse.scroll(0, 500)

監(jiān)控鼠標事件 :

from pynput import mouse


def on_move(x, y):
    print('Pointer moved to {o}'.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:
        return False


def on_scroll(x, y, dx, dy):
    print('scrolled {0} at {1}'.format(
        'down' if dy < 0 else 'up',
        (x, y)))


while True:
    with mouse.Listener(no_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
        listener.join()

鍵盤輸入用法:

from pynput.keyboard import Key, Controller

keyboard = Controller()
# 按下空格和釋放空格
# Press and release space
keyboard.press(Key.space)
keyboard.release(Key.space)
# 按下a鍵和釋放a鍵
# Type a lower case A ;this will work even if no key on the physical keyboard is labelled 'A'
keyboard.press('a')
keyboard.release('a')

# Type two upper case As
keyboard.press('A')
keyboard.release('A')
# or
with keyboard.pressed(Key.shift):
    keyboard.press('a')
    keyboard.release('a')

# type 'hello world ' using the shortcut type method
keyboard.type('hello world')

鍵盤監(jiān)聽:

from pynput import keyboard


def on_press(key):
    try:
        print('alphanumeric key {0} pressed'.format(key.char))
    except AttributeError:
        print('special key {0} pressed'.format(key))


def on_release(key):
    print('{0} released'.format(key))
    if key == keyboard.Key.esc:
        return False


while True:
    with keyboard.Listener(
            on_press=on_press,
            on_release=on_release) as listener:
        listener.join()

按鍵記錄器

# -*- coding:utf-8 -*-
import time
from pynput.keyboard import Key, Controller, Listener


keyboard = Controller()
keys = []


def on_press(key):
    string = str(key).replace("'", "")


def on_release(key):
    global keys
    string = str(key).replace("'", "")
    keys.append('\r' + string)
    main_string = "".join(keys)
    print(main_string)
    if len(main_string) > 15:
        with open('D:\keys.txt', 'a') as f:
            f.write(main_string)
            keys = []


def write_to_file(key):
    letter = str(key)
    letter = letter.replace("'", "")
    with open("./log.txt", 'a') as f:
        f.write(letter)


if __name__ == '__main__':
    # with Listener(on_press=write_to_file) as listener:
    #     listener.join()

    with Listener(on_press=on_press, on_release=on_release) as listener:
        listener.join()
    pass

Python 編寫簡易木馬程序

:https://blog.csdn.net/weixin_34405261/article/details/113554335

win32process

# -*- coding:utf-8 -*-

import psutil
import win32gui
import win32process
from ctypes import *

user32 = windll.user32
kernel32 = windll.kernel32
ps_api = windll.psapi
current_window = None


def func_test_window():
    app = win32gui.GetWindowText(67526)
    if win32gui.IsWindowVisible(67526) and win32gui.IsWindowEnabled(67526):
        thread_id, process_id = win32process.GetWindowThreadProcessId(67526)
        process = psutil.Process(process_id)
        print(process.name(), process_id)
        proc = psutil.Process(pid=process_id)
        print(proc.name())
        print(app)


def get_current_process():
    # 獲取最上層的窗口句柄
    hwnd = user32.GetForegroundWindow()

    # 獲取進程 id
    pid = c_ulong(0)
    user32.GetWindowThreadProcessId(hwnd, byref(pid))

    # 將進程ID 存入變量中
    process_id = pid.value

    # 申請內(nèi)存
    char_array = create_string_buffer(b"0" * 512)
    h_process = kernel32.OpenProcess(0x400 | 0x10, False, pid)
    ps_api.GetModuleBaseNameA(h_process, None, byref(char_array), 512)

    # 讀取窗口標題
    window_title = create_string_buffer(b"0" * 512)
    length = user32.GetWindowTextA(hwnd, byref(window_title), 512)

    print(f"PID:{process_id} - {char_array.value} - {window_title.value}")

    # 關(guān)閉 handles
    kernel32.CloseHandle(hwnd)
    kernel32.CloseHandle(h_process)
    pass


if __name__ == '__main__':
    get_current_process()
    pass

Python MFC GUI

使用 pywin32編寫 windows的GUI (《python 寶典》)
:https://wenku.baidu.com/view/1f4eb95df011f18583d049649b6648d7c0c70830.html

Python win32 庫進行內(nèi)存讀寫

Python win32庫進行內(nèi)存讀寫:

  • 游戲輔助:https://www.jianshu.com/p/0bddab537860
  • 植物大戰(zhàn)僵尸 輔助:https://www.jianshu.com/p/ee890eb0d8d6

:https://tieba.baidu.com/p/1297024013?red_tag=3286293802

Python 游戲輔助

:https://www.jianshu.com/u/dd32b7845ea9

4、python 找圖 找色

?一文講透,經(jīng)典Python圖像處理庫,帶你領(lǐng)略Pillow的強大魅力:https://baijiahao.baidu.com/s?id=1730140116378756711

關(guān)鍵字:python 找圖 找色? ||??win32gui win32api win32con

python 能做類似于按鍵精靈 那種桌面找圖返回坐標么?:https://www.52pojie.cn/thread-1432042-1-1.html

Python實現(xiàn)按鍵精靈(二) - 找圖找色:https://www.bbsmax.com/A/amd0KBKj5g/

python 操作 winAPI:https://www.cnblogs.com/liming19680104/p/11988565.html

pywin32庫 : Python 操作 windows 系統(tǒng) API

關(guān)鍵字:Python GetWindowThreadProcessId

Python 實現(xiàn)按鍵精靈找色點擊功能,使用 pywin32 和 Pillow 庫:https://blog.csdn.net/lrnboy/article/details/85227548文章來源地址http://www.zghlxwxcb.cn/news/detail-494412.html

到了這里,關(guān)于pywin32庫 : Python 操作 windows 系統(tǒng) API的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔相關(guān)法律責任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • Python pywin32實現(xiàn)word和Excel的處理

    Python pywin32實現(xiàn)word和Excel的處理

    pywin32處理Word和Excel的一些事 我們知道Python處理word和Excel的可以借助第三庫python-docx、xlrd、xlwt和openpyxl等實現(xiàn),但這些模塊只支持基本的讀寫操作,如果要實現(xiàn)一些較為深入功能,就要看模塊是否有相應(yīng)功能支持了。 例如將word和Excel轉(zhuǎn)為pdf,在word和Excel里面執(zhí)行VBA實現(xiàn)特殊功

    2024年02月04日
    瀏覽(20)
  • 【Python】解決pywin32各種常見問題及中英文手冊下載(詳細)

    【Python】解決pywin32各種常見問題及中英文手冊下載(詳細)

    目錄 前言 一、中英文手冊獲取 二、各種常見問題 1. ModuleNotFoundError: No module named \\\'win32xxx\\\' 2.?ImportError:DLL load failed while importing win32xxx: 找不到指定的模塊。 方法一 方法二 方法三 3. pywintypes.error: (2, \\\'XXX\\\', \\\'系統(tǒng)找不到指定的文件。\\\') 總結(jié) pywin32是針對微軟Windows的Python擴展,p

    2024年02月07日
    瀏覽(19)
  • Electron 適配 Windows 7 32位操作系統(tǒng)

    Electron 適配 Windows 7 32位操作系統(tǒng)

    1)electron v10.4.7 2)npm 13.14.0 Index of /download/release/v13.14.0/ 1)系統(tǒng)需升級為最低SP1版本的OS; 2)必須安裝的.NET Framework 最低版本為4.6(本例中安裝的是v4.6.2); 3)以防報錯,最好安裝微軟常用運行庫合集; 1)下載SP1升級包,并安裝; 2)等待安裝完成,重啟計算機; 3)安裝微

    2024年02月05日
    瀏覽(21)
  • jenkins構(gòu)建時,報錯ERROR: No matching distribution found for pywin32==305

    最近用jenkin構(gòu)建了一個任務(wù),控制臺輸出,出現(xiàn)如下報錯信息: ERROR: Could not find a version that satisfies the requirement pywin32==305 (from versions: none) ERROR: No matching distribution found for pywin32==305 Build step \\\'Execute shell\\\' marked build as failure Finished: FAILURE ? 原因: requirement是需要導入的依賴包文件

    2023年04月27日
    瀏覽(26)
  • pip intall pywin32出現(xiàn) error: subprocess-exited-with-error 錯誤的解決辦法

    問題描述: 安裝pywin32時候報錯: 有朋友說更新一下setuptools就可以了。 方法來自:pip intall 出現(xiàn) error: subprocess-exited-with-error 錯誤的解決辦法_Jackfled的博客-CSDN博客_subprocess-exit 可惜我測試了,沒用。 報錯: error: subprocess-exited-with-error_匿名用戶2022的博客-CSDN博客? 還有另外一

    2024年02月12日
    瀏覽(38)
  • 服務(wù)器pip3配置requirements.txt時候could not find a version that satisfies the requirement pywin32

    服務(wù)器pip3配置requirements.txt時候could not find a version that satisfies the requirement pywin32

    服務(wù)器安裝pywin32報錯: ?這個沒解決我的問題: pycharm安裝pywin32 報錯:No matching distribution found for pywin32_棠寧的博客-CSDN博客_no matching distribution found for pywin32 然后還有人這樣: Could not find a version that satisfies the requirement win32api (from versions: ) No matching distribution found for win32api

    2024年02月05日
    瀏覽(99)
  • Linux操作系統(tǒng)網(wǎng)絡(luò)模塊

    Linux操作系統(tǒng)的網(wǎng)絡(luò)模塊是負責網(wǎng)絡(luò)通信的核心部分。它通過實現(xiàn)各種協(xié)議和算法,使得計算機能夠在網(wǎng)絡(luò)中進行數(shù)據(jù)交換和通信。網(wǎng)絡(luò)模塊主要包括以下幾個方面的功能: (1)IP協(xié)議棧:負責處理網(wǎng)絡(luò)層的數(shù)據(jù)包,實現(xiàn)IP地址的分配、路由選擇等功能。 IP協(xié)議棧是網(wǎng)絡(luò)模塊

    2023年04月18日
    瀏覽(22)
  • 操作系統(tǒng)實驗-添加一個內(nèi)核模塊

    操作系統(tǒng)實驗-添加一個內(nèi)核模塊

    參考用書: 《操作系統(tǒng)實踐:基于Linux的應(yīng)用與內(nèi)核編程》 一.添加一個內(nèi)核模塊 1.1需求分析 對于一個應(yīng)用程序而言,源代碼經(jīng)編譯后與標準運行庫鏈接,通過系統(tǒng)調(diào)用執(zhí)行操作系統(tǒng)內(nèi)核中的特權(quán)指令,指令返回的結(jié)果通過系統(tǒng)調(diào)用返回給用戶,完成程序。 由于Linux是單內(nèi)

    2024年02月05日
    瀏覽(27)
  • 基于STM32的智能巡檢小車系統(tǒng)設(shè)計--STM32最小系統(tǒng)、直流電機、直流電源模塊設(shè)計

    基于STM32的智能巡檢小車系統(tǒng)設(shè)計--STM32最小系統(tǒng)、直流電機、直流電源模塊設(shè)計

    作者:車 郵箱:692604135@qq.com 學校:西安工程大學碩士研究生 方向:機器視覺、圖像分割、深度學習 在介紹具體實現(xiàn)功能之前,需要介紹以下模塊。 本課題選擇的單片機是ST(意法半導體)開發(fā)的STM32F407VET6。 這是一款采用Corte-M4為內(nèi)核的高性能32位ARM微控制器。該芯片支持

    2024年02月10日
    瀏覽(96)
  • Python模塊openpyxl & 操作Excel文件

    Python模塊openpyxl & 操作Excel文件

    簡介 ????????openpyxl是一個用于讀取和編寫Excel 2010 xlsx/xlsm/xltx/xltm文件的Python庫。openpyxl以Python語言和MIT許可證發(fā)布。 ????????openpyxl可以處理Excel文件中的絕大多數(shù)內(nèi)容,包括圖表、圖像和公式。它可以處理大量數(shù)據(jù),支持Pandas和NumPy庫導入和導出數(shù)據(jù)。Openpyxl還支持自

    2024年02月10日
    瀏覽(31)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包