Python学习笔记之---如何使用Python操作window窗口

原创 2015年11月20日 10:54:24

1.需求分析
在使用Python编程的时候,通常会遇到一个问题,当前用户打开很多任务,QQ,Wechat,chome浏览器,Firefox浏览器,以及文件夹。那么如何在众多任务中选择并且激活指定的窗口呢。
2. 解决方法分析
因为这些窗口是window平台的,因此我们可以想到的是调用window的库。因此需要导入一些Python的windows库,也就是pywin32,然后查找相关函数,并调用以此达到效果
3.解决步骤
1.安装pytho2.7
2.安装pywin32
4.代码写作与分析:

from win32gui import *

import time
import os

titles = set()
#===================================================
# FuncName:foo
# Desc:
# 
# Para:
# Return:
# Date: 2015-05-20 18:20
# Author: junma
#===================================================
def EnumWindowsProc (hwnd,mouse):
    #if you want to show all the window,pls delete the one line below
    if IsWindow(hwnd) and IsWindowEnabled(hwnd) and IsWindowVisible(hwnd) and GetWindowText(hwnd) != "":
        text = GetWindowText(hwnd)
        titles.add(text)
        classname = GetClassName(hwnd)
        print "the window's text = %s \nhwnd = %d classname = %s" % (text,hwnd,classname)
#         SendMessage(hwnd,win32con.WM_CLOSE,win32con.VK_RETURN,0)
        SetForegroundWindow(hwnd)
        print ShowWindow(hwnd,SW_SHOW)
        time.sleep(3)


def PrintSort_ALL_visable_window():
    EnumWindows(EnumWindowsProc, 1)
    # print "titles = %s" % titles
    lt = [t for t in titles if t]
    lt.sort()
    print lt
    for t in lt:
        print t
# return an Handle of a window
def GetCurForWin():
    for i in range(1,2):
        time.sleep(1)
        hw = win32gui.GetForegroundWindow()
        text = GetWindowText(hw)
        desk = win32gui.GetDesktopWindow()
        print "Current window's hw = %d, desk = %d, text = %s" % (hw,desk,text)

class WindowFinder:
    "Class to find and make focus on a particular Native OS dialog/Window "
    def __init__ (self):
        self._handle = 527588

def find_window(self, class_name, window_name = None):
        "Pass a window class name & window name directly if known to get the window"
        self._handle = win32gui.FindWindow(class_name, window_name)

    def _window_enum_callback(self, hwnd, wildcard):
        if re.match(wildcard, str(win32gui.GetWindowText(hwnd))) != None:
            self._handle = hwnd

    def find_window_wildcard(self, wildcard): 
        "This function takes a string as input and calls EnumWindows to enumerate through all open windows"
        self._handle = None
        win32gui.EnumWindows(self._window_enum_callback, wildcard)

    def set_foreground(self):
        "Get the focus on the desired open window"
        win32gui.SetForegroundWindow(self._handle)

def SetForWin(hwnd):
    SetForegroundWindow(hwnd)
    SetWindowPos(hwnd,HWND_TOP,0,0,0,0,win32con.SWP_SHOWWINDOW)

def GetWindByTitile():
    hwnd = FindWindow(None, "RIDE - Win Operate")
    text = GetWindowText(hwnd)
    print text
    SetForegroundWindow(hwnd)
#     SetFocus(hwnd)
    ShowWindow(hwnd,SW_RESTORE)

if __name__ == '__main__':
    print dir(win32api)
    PrintSort_ALL_visable_window()
    print GetDesktopWindow()
    GetWindByTitile()

代码块

代码块语法遵循标准markdown代码,例如:

@requires_authorization
def somefunc(param1='', param2=0):
    '''A docstring'''
    if param1 > param2: # interesting
        print 'Greater'
    return (param2 - param1 + 1) or None
class SomeClass:
    pass
>>> message = '''interpreter
... prompt'''

代码分析,首先应该获取所有的进程窗口,并且进行过滤,过滤的条件为可视的,而且它的title不能为空
然后通过回调函数获取其hwnd和title

然后根据要激活置顶的窗口名字,查找其hwnd。接着调用两个很重要的函数

  SetForegroundWindow(hwnd) ----设置其为最前,但设置之后并不能让它显示出来,接着就要显示它
  ShowWindow(hwnd,SW_SHOW)
显示的这个函数的第二个参数比较重要,它决定着窗口如何显示

ParametershWnd [in]Type: HWND
A handle to the window.
nCmdShow [in]Type: int
Controls how the window is to be shown. This parameter is ignored the first time an application calls ShowWindow, if the program that launched the application provides a STARTUPINFO structure. Otherwise, the first time ShowWindow is called, the value should be the value obtained by the WinMain function in its nCmdShow parameter. In subsequent calls, this parameter can be one of the following values.
ValueMeaningSW_FORCEMINIMIZE11Minimizes a window, even if the thread that owns the window is not responding. This flag should only be used when minimizing windows from a different thread.
SW_HIDE0Hides the window and activates another window.
SW_MAXIMIZE3Maximizes the specified window.
SW_MINIMIZE6Minimizes the specified window and activates the next top-level window in the Z order.
SW_RESTORE9Activates and displays the window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when restoring a minimized window.
SW_SHOW5Activates the window and displays it in its current size and position.
SW_SHOWDEFAULT10Sets the show state based on the SW_ value specified in the STARTUPINFO structure passed to the CreateProcess function by the program that started the application.
SW_SHOWMAXIMIZED3Activates the window and displays it as a maximized window.
SW_SHOWMINIMIZED2Activates the window and displays it as a minimized window.
SW_SHOWMINNOACTIVE
Displays the window as a minimized window. This value is similar to SW_SHOWMINIMIZED, except the window is not activated.
SW_SHOWNA8Displays the window in its current size and position. This value is similar to SW_SHOW, except that the window is not activated.
SW_SHOWNOACTIVATE4Displays a window in its most recent size and position. This value is similar to SW_SHOWNORMAL, except that the window is not activated.
SW_SHOWNORMAL1Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when displaying the window for the first
Return value
Type:
Type: BOOL
If the window was previously visible, the return value is nonzero.
If the window was previously hidden, the return value is zero.

Python学习笔记---环境变量搭建(Window)

Python的环境在window系统中安装十分简单。1.Python官网的download目录选择window环境下载,一般是Python3的版本。2.直接点击安装,记得选择add path项目。3....

Python - 将window 窗口操作过程包装成脚本函数可被调用

【学习笔记】使用Python对文件进行简单操作

文件处理中常用的Python代码1
  • sealvor
  • sealvor
  • 2016年08月26日 05:45
  • 154

Python学习笔记(2)- Window 平台安装 Python

Window 平台安装 Python: 以下为在 Window 平台上安装 Python 的简单步骤: 打开WEB浏览器访问http://www.python.org/download/ ...

【Unity 3D】学习笔记九:window控件(窗口)

Unity 学习笔记九   学习资料:《Unity 3D游戏开发》 宣雨松   在游戏中,所有的视图都需要依赖窗口来实现,可以把窗口理解为视图的父类。   游戏界面可以由若干的窗口组成,而...

ExtJS:学习笔记五:window窗口-登陆

Ext.onReady(function() { //window继承与panel但不是panel,它有个显现过程 var _window = new Ext.Window({ //始终...

EXTJS 窗口Ext.Window()学习笔记

var win = new Ext.Window({ layout:'fit', //窗口的布局类型,fit表示布局布满整个窗口 width:500, //窗口大小 ...

Python学习笔记-Excel读写操作

需要先安装xlrd(读)、xlwt(写)库 pip install xlrd pip install xlwt 代码如下: import os import sys import xlrd i...

MongoDB 学习笔记(python操作)

交流QQ群:26651479 一、MongoDB 数据库操作   1. 连接数据库     import pymongo     conn = pymongo.Connection() #...
  • daillo
  • daillo
  • 2011年12月01日 14:31
  • 17945

Jython-Java操作Python脚本学习笔记(二)

这里将记录关于使用pydev插件在Eclipse中开发Python,同时使用Jython来实现Java与Python的互操作:    (一)关于下载安装和配置pydev插件和Jython:    ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Python学习笔记之---如何使用Python操作window窗口
举报原因:
原因补充:

(最多只允许输入30个字)