python win32 simple operation method

  • 2020-06-01 10:18:29
  • OfStack

The source of

The beginning is to help a friend to do a key wizard operation wang letter script, after writing all kinds of instability; Later, I saw that python could operate api related to win32, and I happened to be learning python during this period. I felt that it was time to practice my hands

download

Be aware of the Python version and the number of digits, otherwise the installation will fail

Go directly to the above address to find the right version to download and install. Other tools are included

Download is already an executable file, can be executed directly


https://sourceforge.net/projects/pywin32/

How to get the handle

VC or VS tools come with SPY++, you can get handle information, you don't have this, please see the next

That's right, it's a button Sprite (not for advertising, but for the first time looking for handle information), and it's easy to use

use

Handle to the query


#  Query handle by class name and title name, 
hwnd = win32gui.FindWindow("Tfrm_YzzPlayer"," Leaf pig hand tour simulator ")
#  Looks for a clause handle to the specified handle. The last two arguments are the class name and title of the subclass None
hwnd = win32gui.FindWindow(hwnd,None,"sub_class","sub_title")

Modify window size


#  There is no way to directly modify the window size, but it can be curvilinear, and several parameters represent handles , Starting point coordinates , Width height , Whether to redraw the interface   , if you want to change the size of the window, you must specify the starting point coordinates, if there is no requirement on the starting point coordinates, just write; If you want to keep it where it was before, you need to get the previous border position and then call the method 
win32gui.MoveWindow(hwnd,20,20,405,756,True)

The front desk background


#  Specifies that the handle is set to the foreground, that is, activated 
win32gui.SetForegroundWindow(hwnd)
#  Set it to the background 
win32gui.SetBkMode(hwnd, win32con.TRANSPARENT)

The keys


#  There are two options here   You can use win32gui Package and win32api The package, currently not deeply understood, feels like 1 Samples of each 1 There are also PostMessage with SendMessage Both are optional, according to the other documents SendMessage Is synchronous and returns only after successful execution PostMessage It's done asynchronously, it's done directly, it's just added to the queue 
#  Several parameters are respectively :  Handle to the operation  ,  Type of button ( Press or bounce ),  Key code (most function keys in win32con For all commonly used Numbers or letters, look them up directly ASII Code, such as A 65  And so on), relative to the position in the handle ( You need to use it here win32api.MAKELONG(x,y) Converts two addresses to 1 A long address; 
#  In this case, you can do things in the background 
#  It's important to note that each 1 There are two processes to press down and up the button, than if we want to press Enter Key, you need to have two lines of code, number one 2 The parameters are respectively  KEYDOAWN with  KEYUP  , if it is a key combination, you can press the key combination separately and then play it separately 
# win32gui.PostMessage(tid, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
# win32gui.SendMessage(tid, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
win32api.SendMessage(hwd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, long_position)
win32api.PostMessage(hwd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, long_position)

Send a message

There are two ways to do this. One is to find the handle to the input box and set the key type to SETTEXT

Another way is to put the required input into the paste board, directly paste can be


#  way 1 Explain yourself on the network when testing 1 It was not successful, because I was operating the software in the android emulator and could not find the handle of the input box 
win32gui.SendMessage(tid, win32con.WM_SETTEXT,None, ' hello')
#  way 2 , passed the test   It's just putting the content in the clipboard, straight up ctrl + v The feeling applies to situations where a specific handle to the input box cannot be found, but the focus is already in the input box 
#  Define two methods to read and write to the clipboard, noting that the target system is coded the same way 
def getText():
#  Reading board 
w.OpenClipboard()
d = w.GetClipboardData(win32con.CF_TEXT)
w.CloseClipboard()
return d
def setText(aString):
#  Write clipboard 
w.OpenClipboard()
w.EmptyClipboard()
w.SetClipboardData(win32con.CF_TEXT, aString.encode(encoding='gbk'))
w.CloseClipboard()

Code sample

The following code reads each line from one text, then looks up the contact in the android emulator, and sends a message with the specified content.


# coding: utf-8
import win32gui, win32api, win32con
import time
import win32clipboard as w

import logging


def click_position(hwd, x_position, y_position, sleep):
  """
   Click the left mouse button to specify coordinates 
  :param hwd: 
  :param x_position: 
  :param y_position: 
  :param sleep: 
  :return: 
  """
  #  The two 16 The values of bits are concatenated into 1 a 32 Bit address coordinates 
  long_position = win32api.MAKELONG(x_position, y_position)
  # win32api.SendMessage(hwnd, win32con.MOUSEEVENTF_LEFTDOWN, win32con.MOUSEEVENTF_LEFTUP, long_position)
  #  Click on the left? 
  win32api.SendMessage(hwd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, long_position)
  win32api.SendMessage(hwd, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, long_position)
  time.sleep(int(sleep))


def getText():
  #  Reading board 
  w.OpenClipboard()
  d = w.GetClipboardData(win32con.CF_TEXT)
  w.CloseClipboard()
  return d


def setText(aString):
  #  Write clipboard 
  w.OpenClipboard()
  w.EmptyClipboard()
  w.SetClipboardData(win32con.CF_TEXT, aString.encode(encoding='gbk'))
  w.CloseClipboard()


def input_content(hwd, content, sleep, is_enter):
  """
   Find the input from the station sticker 
  :param hwd: 
  :param content: 
  :param sleep: 
  :param is_enter  Whether to enter at the end enter key , Content and enter Interval between 1 seconds 
  :return: 
  """
  setText(content)
  time.sleep(0.3)
  click_keys(hwd, win32con.VK_CONTROL, 86)
  if is_enter:
    time.sleep(1)
    click_keys(hwd, win32con.VK_RETURN)
  time.sleep(sleep)


def click_keys(hwd, *args):
  """
   Define combination keys 
  :param hwd: 
  :param args: 
  :return: 
  """
  for arg in args:
    win32api.SendMessage(hwd, win32con.WM_KEYDOWN, arg, 0)
  for arg in args:
    win32api.SendMessage(hwd, win32con.WM_KEYUP, arg, 0)


def wangwang_operation(hwd, salesname, content1, content2):
  """
   Operation of ali wangwang 
  :param hwd:  handle 
  :param salesname: 
  :param content1:  send 1
  :param content2:  send 2
  :return: 
  """
  #  Contact tag below 
  click_position(hwd, 200, 685, 2)
  #  Add friend button 
  click_position(hwd, 372, 44, 3)
  #  Search for friends 
  input_content(hwd, salesname, 3, False)
  #  Click on the search 
  click_position(hwd, 345, 117, 5)
  #  Click send message 
  click_position(hwd, 350, 700, 3)
  #  Send a message 1
  input_content(hwd, content1, 1, False)
  click_keys(hwd, win32con.VK_CONTROL, win32con.VK_RETURN)
  time.sleep(1)
  input_content(hwd, content2, 1, False)
  click_keys(hwd, win32con.VK_CONTROL, win32con.VK_RETURN)
  time.sleep(1)
  #  Return to original state 
  click_position(hwd, 20, 45, 1)
  time.sleep(1)
  click_position(hwd, 20, 45, 1)


def wangwang_operation_by_file(hwd, file, content1, content2):
  with open(file, 'r') as f:
    line = f.readline()
    while len(line) >= 1:
      try:
        line = line.replace('\r', '').replace('\n', '')
        print(" Are dealing with    %s   ....................................." % line)
        wangwang_operation(hwd, line, content1, content2)
        line = f.readline()
      except BaseException as e:
        print(" To deal with  %s  An error occurred when the ............." % line)
        logging.exception(e)


if __name__ == "__main__":
  #  To find the handle 
  hwnd = win32gui.FindWindow("Tfrm_YzzPlayer", " Leaf pig hand tour simulator ")
  if int(hwnd) <= 0:
    print(" The emulator was not found, exit the process ................")
    exit(0)
  print(" Query to the simulator handle : %s " % hwnd)
  win32gui.MoveWindow(hwnd, 20, 20, 405, 756, True)
  time.sleep(2)
  #  Screen coordinates to client coordinates 
  # print(win32gui.ScreenToClient(hwnd, (1446, 722)))
  #  Set it to the foreground 
  # win32gui.SetForegroundWindow(hwnd)
  #  Set it to the background 
  win32gui.SetBkMode(hwnd, win32con.TRANSPARENT)
  time.sleep(2)
  #  The following after 3 Three parameters are represented respectively :  The file path   Greeting sentence   AD 
  wangwang_operation_by_file(hwnd, "D:/2.txt", " hello ", " Test advertising slogan ")

Related articles: