Python delicious everyday (36)-use python to implement spy ++

Source: Internet
Author: User
ArticleDirectory
    • Principles of spy ++
    • Functions corresponding to pywin32
    • Code Implementation
    • Demo

Spy ++ is a tool developed by Microsoft to obtain window information. The implementation principle is actually not difficult, simply by calling some specific windows APIs. As a result, I plan to use python to implement a simple version tool named pyspy ++. Python generally uses the pywin32 library to call windows APIs. I use pyqt4 as the interface library.

Principles of spy ++

In spy ++, the most common function is to identify the window. Windows APIs are mainly used:

Get the current mouse position:

Bool getcursorpos (lppoint );

Obtains the window handle at the specified position.:

Hwnd windowfrompoint (point );

Retrieve window category:

Int Getclassname (hwnd, lptstr lpclassname, Int Nmaxcount );

Obtain the window content or title:

Method 1:

Int Getwindowtext (hwnd, lptstr lpstring, Int Nmaxcount );

This API sometimes cannot get the value of some controls. Therefore, use method 2.

Method 2:

Send the wm_gettext message to the window:

Lresult sendmessage (hwnd, uint MSG, wparam, lparam );

Highlighted window:

Obtain the size of the current window and draw a rectangle.

Bool getwindowrect (hwnd, lprect );

Bool rectangle (
HDC, // Handle to DC
Int Nleftrect, // X-coord of upper-left corner of rectangle
Int Ntoprect, // Y-coord of upper-left corner of rectangle
Int Nrightrect, // X-coord of lower-right corner of rectangle
Int Nbottomrect // Y-coord of lower-right corner of rectangle
);

After you move the mouse away from the window, the window must be restored and refreshed again:

Bool invalidaterect (
Hwnd, // Handle to window
Const rect * Lprect, // Rectangle coordinates
Bool berase // Erase state
);

Bool updatewindow (
Hwnd//Handle to window
);

Bool redrawwindow (
Hwnd, // Handle to window
Const rect * Lprcupdate, // Update rectangle
Hrgn hrgnupdate, // Handle to update Region
Uint flags // Array of redraw flags
);

Functions corresponding to pywin32

Call the Windows API in Python, first download pywin32, address: http://pywin32.sourceforge.net/

After the installation is complete, open the help document python for Windows documentation, which contains everything you need and can be viewed at any time.

Common APIs are in the WIN32API module, interface-related APIs are in the win32gui module, and some constants defined in API parameters are in the win32con module. The above Windows API corresponds to the function in pywin32:

(INT, INT) = Win32gui. Getcursorpos ()
Int = Win32gui. Windowfrompoint (Point)
String = Win32gui. Getclassname (Hwnd)
String = Win32gui. Getwindowtext (Hwnd)
Int = Win32gui. Sendmessage (Hwnd, message, wparam, lparam)
(Left, top, right, bottom) = Win32gui. Getwindowrect (Hwnd)
Win32gui. Rectangle (HDC, leftrect, toprect, rightrect, bottomrect)
Win32gui. Invalidaterect (Hwnd, rect, erase)
Win32gui. Updatewindow (Hwnd)
Win32gui. Redrawwindow (Hwnd, rcupdate, hrgnupdate, flags)

Code Implementation

The interface library uses pyqt4. For more information, see pyqt4 learning materials in my previous blog.

The tool dialog box window has two controls: one is the qlabel control and the other is the qtextedit control. The qlabel control is the one used to capture the window after the mouse is pressed down, And the qtextedit control is used to display the window information. To allow qtextedit to respond to custom mouse events, I created a custom qlabel control spylabel that inherits from the qlabel.

Class Spylabel (qtgui. qlabel ):
Def   _ Init __ (Self, parent = None ):
Qtgui. qlabel. _ Init __ (Self, parent)
Self. Parent = Parent
Self. Spying = False
Self. rectanglepen = Win32gui. createpen (win32con. ps_solid, 3 , WIN32API. RGB ( 255 , 0, 0 ))
Self. prevwindow = None
Self. Setcursor(Qtcore. QT. sizeallcursor)

To process mouse movement events in spylabel:

Def Mousemoveevent (self, event ):
If Self. Spying:
Curx, Cury = Win32gui. getcursorpos ()
Hwnd = Win32gui. Windowfrompoint (Curx, Cury ))

IfSelf. checkwindowvalidity (hwnd ):
IfSelf. prevwindow:
Self. refreshwindow (self. prevwindow)
Self. prevwindow=Hwnd
Self. highlightwindow (hwnd)
Self. display1_winformation (hwnd)

Mouse release event:

Def Mousereleaseevent (self, event ):
If Self. Spying:
If Self. prevwindow:
Self. refreshwindow (self. prevwindow)
Win32gui. releasecapture ()
Self. Spying = False

Function of the highlighted window:

Def Highlightwindow (self, hwnd ):
Left, top, right, bottom = Win32gui. getwindowrect (hwnd)
Windowdc = Win32gui. getwindowdc (hwnd)
If Windowdc:
Prevpen = Win32gui. SelectObject (windowdc, self. rectanglepen)
Prevbrush = Win32gui. SelectObject (windowdc, win32gui. getstockobject (win32con. hollow_brush ))

Win32gui.Rectangle(Windowdc, 0, 0, right-Left, bottom-Top)
Win32gui. SelectObject (windowdc, prevpen)
Win32gui. SelectObject (windowdc, prevbrush)
Win32gui. releasedc (hwnd, windowdc)

Refresh window function:

Def Refreshwindow (self, hwnd ):
Win32gui. Invalidaterect (Hwnd, none, true)
Win32gui. Updatewindow (Hwnd)
Win32gui. Redrawwindow (Hwnd,
None,
None,
Win32con. rdw_frame |
Win32con. rdw_invalidate |
Win32con. rdw_updatenow |
Win32con. rdw_allchildren)

Display window information:

Def Display1_winformation (self, hwnd ):
Classname = Win32gui. getclassname (hwnd)
Buf_size =   1   + Win32gui. Sendmessage (Hwnd, win32con. wm_gettextlength, 0, 0)
Buffer = Win32gui. pymakebuffer (buf_size)
Win32gui. Sendmessage (Hwnd, win32con. wm_gettext, buf_size, buffer)
Windowtext = Buffer [: buf_size]

Try:
Windowtext=Unicode (windowtext,'GBK')
Except:
Pass

Message= [ ' Handle: \ t '   + STR (hwnd ),
' Class Name: \ t '   + Classname,
' Window text: \ t '   + Windowtext]
Self. Output ( ' \ R \ n ' . Join (Message ))

Note that the sendmessage function above requires an allocated buffer to obtain the returned content. Here we use:

Buffer = Win32gui. pymakebuffer (buf_size)

Since the returned content can contain Chinese characters, Unicode (windowtext, 'gbk') is used for conversion.

Demo

 

Binary Download:

Http://pyspyplusplus.googlecode.com/files/pyspy++.exe

Source code:

Http://code.google.com/p/pyspyplusplus/

 

 

Python daily delicious series (total)

Python daily delicious (31)-insert sorting of Python data structures and algorithms

Python daily delicious (32)-Python data structure and algorithm heap sorting

Python every day (33)-five minutes to understand metaclasses [go]

Python daily delicious (34)-decorators

Python delicious everyday (35)-Premium Lambda

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.