Win32API Win32gui Win32con Window handle common methods of sending messages

Source: Internet
Author: User
Tags message queue

Pywin32 is a python library that provides Python access to Windows API extensions, and provides a full range of Windows constants, interfaces, threads, COM mechanisms, and more.

1. Find the window handle through the class name and title and get the window position and size

Import Win32guiimport win32apiclassname = "Mozillawindowclass" TitleName = "Baidu a bit, you know-Mozilla Firefox" #获取句柄hwnd = win32g Ui. FindWindow (classname, TitleName) #获取窗口左上角和右下角坐标left, top, right, bottom = Win32gui. GetWindowRect (HWND)

2. Get the clause handle from the parent handle

def get_child_windows (parent):            "'         gets all child window handles to parent     return child window handle List     '         if not parent:                 return          hwndchildlist = []         Win32gui. Enumchildwindows (parent, Lambda hwnd, Param:param.append (HWND),  hwndchildlist)              return hwndchildlist # Gets the class name and title of a handle named title = Win32gui. GetWindowText (hwnd)     clsname = Win32gui. GetClassName (hwnd)     #获取父句柄hwnd类名为clsname的子句柄hwnd1 = Win32gui. FindWindowEx (hwnd, none, Clsname, none)

3. Mouse positioning and click

#鼠标定位到 (30,50) Win32API. Setcursorpos ([30,150]) #执行左单键击, if you need to double-click the delay a few milliseconds and then click once to 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)

4. Send the ENTER key

Win32api.keybd_event (13,0,0,0) win32api.keybd_event (13,0,win32con. keyeventf_keyup,0)

5. Close the window

Win32gui. PostMessage (Win32lib.findwindow (classname, TitleName), Win32con. Wm_close, 0, 0)

First, import Win32gui, Win32con
Second, use Win32gui. FindWindow Find the target program:
Win = Win32gui. FindWindow (None, ' User Login ')
Third, use Win32gui. FindWindowEx Find the target text box:
Tid = Win32gui. FindWindowEx (Win, none, ' Edit ', none)
Four, use Win32gui. SendMessage send text to the target text box:
Win32gui. SendMessage (Tid, Win32con. Wm_settext, None, ' hello ')

Of course, you can continue to find the next text box:
Username = Win32gui. FindWindowEx (Win, Tid, ' Edit ', None)

Just haven't found the function to add a return to the string, in Notepad can be implemented, do not know why not here. If the heroes have the hope of knowing, please enlighten me.
This is the first time we have studied here. In case you forget, keep it here for later use.
Update: You have found a way to send a carriage return:
Win32gui. SendMessage (Tid, Win32con. Wm_settext, None, ' hello ')
Win32gui. PostMessage (Tid, Win32con. Wm_keydown, Win32con. Vk_return, 0)
Win32gui. PostMessage (Tid, Win32con. Wm_keyup, Win32con. Vk_return, 0)

Instance:

Import Win32guiimport Win32conimport Win32API# Search the main window from the top-level window to search for child windows# FindWindow (lpclassname=none, lpwindowname=none) window class Name window title name handle = Win32gui. FindWindow ("Notepad", None)# get window position left, top, right, bottom = Win32gui. GetWindowRect (handle)#获取某个句柄的类名和标题title = Win32gui. GetWindowText (handle) Clsname = Win32gui. GetClassName (handle)# Print Handle# decimal print (handle)# Hex Print ("%x"% (handle))# Search Child window# enumerate child windows hwndchildlist = [] Win32gui. Enumchildwindows (handle, Lambda hwnd, Param:param.append (HWND), hwndchildlist)# FindWindowEx (hwndparent=0, hwndchildafter=0, Lpszclass=none, Lpszwindow=none) if the parent window handle is not 0, The subform is searched backwards from hwndchildafter in the order of Z-index, or the first subform starts the search. child window class Name child window caption Subhandle = Win32gui. FindWindowEx (Handle,0,"EDIT", None)# Gets the window's menu handle menuhandle = Win32gui. GetMenu (Subhandle)# Get a submenu or drop-down menu handle# Parameter: Menu Handle submenu index number Submenuhandle = Win32gui. GetSubMenu (Menuhandle,0)# get the marker in the menu item, note that the delimiter is indexed# Parameters: Submenu handle Item index number Menuitemhandle = Win32gui. Getmenuitemid (Submenuhandle,0)# Send message, join message queue, no return# parameter: Handle message type WParam iparamwin32gui.postmessage (Subhandle, Win32con. WM_COMMAND, Menuitemhandle,0)# wparam is defined as a 32-bit integer, and high Word is his 31 to 16 bit, and low word is its 15 to 0 bits.# When the parameters are more than two, wparam and lparam are not enough, you can split the wparam into two int16 to use.# this time in Python remember to shift the HIWORD constant to the left by 16 bits, then add loword, i.e. wparam = Hiword<<16+loword.# Next Box content changes# parameters: The handle of the box, the content of the message, the index of which item of the selected box under the parameter, the option to start with 0, and if the value is-1, the current option is removed from the combo box list and the current option is empty;# Cb_handle is the next marquee handle, pcb_handle the box under the parent window handle if Win32API. SendMessage (Cb_handle, Win32con. Cb_setcursel,1,0) = =1:# The parent window of the marquee command# Parameters: Parent window handle; Parameters: WParam: High-level representation type, low-level representation of content; parameter iparam, bottom marquee handle# Cbn_selendok When a user selects a valid list item to send, the parent form is prompted to process the user's selection. LoWord is the ID of the combo box. HiWord is the value of Cbn_selendok. Win32API. SendMessage (Pcb_handle, Win32con. WM_COMMAND,0x90000, Cb_handle)# Cbn_selchange When a user changes the selection of a list item, the notification is sent whether the user is selected by the mouse or through the arrow keys. LoWord is the ID of the combo box. HiWord is the value of Cbn_selchange. Win32API. SendMessage (Pcb_handle, Win32con. WM_COMMAND,0x10000, Cb_handle)# Sets the contents of the text box and returns True when the window has finished processing. Chinese need to encode into GBK# Parameters: Handle, message type, parameter wparam, no need to use, parameter Iparam, string Win32API to set. SendMessage (handle, Win32con. Wm_settext,0, Os.path.abspath (fgfilepath). Encode (' GBK '))# control clicks OK, processing message returns 0# parameter: Window handle; Message type; Parameter wparam hiword is 0 (not used), LoWord is the ID of the control; Parameter Iparam 0 (not used) to determine the handle of the control Win32API. SendMessage (Mhandle, Win32con. WM_COMMAND,1, Confirmbtn_handle)# Gets the length of the window text without a truncated null character# Parameters: Window handle; message type; parameter wparam; parameter iparambufsize = Win32API. SendMessage (Subhandle, Win32con. Wm_gettextlength,0,0) +1# Use API to generate BUFFERSTRBUF = Win32gui. Pymakebuffer (bufSize) print (STRBUF)# Send message for text content# Parameters: Window handle; message type; text size; storage location length = Win32gui. SendMessage (Subhandle, Win32con. Wm_gettext, BufSize, Strbuf)# reverse content, convert to string# text = str (strbuf[:-1]) address, length = Win32gui. Pygetbufferaddressandlen (strbuf) Text = Win32gui. Pygetstring (address, length)# print (' text: ', text)# MOUSE Click event#鼠标定位到 (30,50) Win32API. Setcursorpos ([30,150])#执行左单键击, if you need to double-click the delay a few milliseconds and then click once to 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)# Send carriage return win32api.keybd_event (13,0,0,0) Win32api.keybd_event (13,0,win32con. Keyeventf_keyup,0)# Close the window Win32gui. PostMessage (Win32lib.findwindow (classname, TitleName), Win32con. Wm_close,0,0)# Check if the window is minimized if it is maximized if (Win32gui. Isiconic (hwnd)):# Win32gui. ShowWindow (hwnd, Win32con.sw_shownormal) Win32gui. ShowWindow (hwnd,8) Sleep (0.5)# Sw_hide: Hides the window and activates other windows. Ncmdshow=0.# Sw_maximize: Maximizes the specified window. Ncmdshow=3.# Sw_minimize: Minimizes the specified window and activates the Next top-level window in the Z-order. Ncmdshow=6.# Sw_restore: Activates and displays the window. If the window is minimized or maximized, the system restores the window to its original size and position. The application should specify this flag when the minimized window is restored. Ncmdshow=9. # Sw_show: Activates and displays the window in its original position at the original size. Ncmdshow=5. # Sw_showdefault: The display state is set according to the SW_FLAG flag specified in the STARTUPINFO structure, and the STARTUPINFO structure is passed to the CreateProcess function by the program that initiated the application. ncmdshow=10. # sw_showmaximized: Activates the window and maximizes it. Ncmdshow=3. # sw_showminimized: Activates the window and minimizes it. ncmdshow=2. # sw_showminnoactive: Window is minimized, activation window still remains active. Ncmdshow=7. # Sw_showna: Displays the window in its original state. The activation window still remains active. Ncmdshow=8. # sw_shownoactivate: Displays the window with the last size and status of the window. The activation window still remains active. Ncmdshow=4. # Sw_shownormal: Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and size. The application should specify this flag the first time the window is displayed. Ncmdshow=1. 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21st
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
# Win32 Although the keyboard can also be controlled, it is not as convenient as using Pyuserinput. It is important to note that the interface parameters may vary under windows and Macs. From pymouse import pymousefrom pykeyboard Import PYKEYBOARDM = Pymouse () k = Pykeyboard () x_dim, Y_dim = M.screen_size ()# mouse click M.click (x_dim/2, y_dim/2,1)# Keyboard Input k.type_string (' Hello, world! ')# Hold down a key K.press_key (' H ')# Release a key K.release_key (' H ')# Press and release, tap a key K.tap_key (' E ')# TAP supports duplicate intermittent click Key K.tap_key (' L ', n=2,interval= 5) # Send judgment Text k.type_string ( #创建组合键k. Press_key (K.alt_key) K.tap_key (K.tab_key) K.release_key (k.alt_ Key) # special function Key K.tap_key (K.function_keys[5]) # tap F5K.TAP_ Key (K.numpad_keys[ ' home ') # Tap  ' home ' on the Numpadk.tap_key ( K.numpad_keys[5], N=3) # Tap 5 on the Numpad, Thrice# mac system K.press_keys ([ ' shift ',  ' 3 ']) # Windows system K.press_ Keys ([K.windows_l_key, d ']) where pymouseevent and pykeyboardevent can also be used to listen for mouse and keyboard events input   

Win32API Win32gui Win32con Window handle common methods of sending messages

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.