473,657 Members | 2,435 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Get a control over a window

Hi,

I was wondering how do I get control over a window (Win32).
to be more specific, I need to find a handle to a window of a certain
program and minimize the window.

May 15 '07 #1
5 8282
On May 15, 8:06 am, Tom Gur <gur....@gmail. comwrote:
Hi,

I was wondering how do I get control over a window (Win32).
to be more specific, I need to find a handle to a window of a certain
program and minimize the window.
It sounds pretty complicated to me, but here's what I found:

http://mail.python.org/pipermail/pyt...er/352639.html
http://forums.devshed.com/python-pro...ws-132273.html

That should get you started. If you figure it out, post your code so
the rest may benefit.

Mike

May 15 '07 #2
On 15 Mai, 15:06, Tom Gur <gur....@gmail. comwrote:
Hi,

I was wondering how do I get control over a window (Win32).
to be more specific, I need to find a handle to a window of a certain
program and minimize the window.

There are many ways to get the handle of a window.
Assuming you have ctypes at hand, you could try:
>user32 = ctypes.windll.u ser32
hwnd = user32.FindWind owA(classname, title)
if hwnd:
user32.PostMess ageA(hwnd, WM_SYSCOMMAND, SC_ICON, 0)
If you need it more acurate you could search MSDN
for how to enumerate all running processes and get the
handles of their windows. Process32First (...) could be
a start for reading.

Jürgen

May 15 '07 #3
Tom Gur <gu*****@gmail. comwrote:
I was wondering how do I get control over a window (Win32).
to be more specific, I need to find a handle to a window of a certain
program and minimize the window.
Here's a function which returns a list of all windows where the class is
'PuTTY' or the title contains a particular string:

from win32gui import EnumWindows, GetClassName, EnumChildWindow s
from win32ui import CreateWindowFro mHandle, MessageBox

def toplevelWindows ():
res = []
def callback(hwnd, arg):
name = GetClassName(hw nd)
w = CreateWindowFro mHandle(hwnd)
title = w.GetWindowText ()
if "'s password:" in title or name=='PuTTY':
res.append(w)
EnumWindows(cal lback, 0)
return res

You can minimize a window once you have found it by calling ShowWindow
(or SetWindowPlacem ent).

If you don't want to depend on Python's win32 extensions being installed
then you can also do the same thing using ctypes.

In either case be very careful that you are only picking up the windows
you wanted to find as enumerating top level windows will return a lot of hidden windows and if you start messing with these you will probably need to reboot your system.

Here's something adapted from some stuff where I was playing with ctypes
(so you could probably cut out a lot of crud). It's a complete program
which will find a Firefox window with a specified string in the title
and minimize it (without the test for the classname it will also minimize
the command window you run it from).
--------- minimize.py -------------
#
# Minimize a specified window.
#
import sys
import ctypes
from ctypes import *

def _stdcall(dllnam e, restype, funcname, *argtypes):
# a decorator for a generator.
# The decorator loads the specified dll, retrieves the
# function with the specified name, set its restype and argtypes,
# it then invokes the generator which must yield twice: the first
# time it should yield the argument tuple to be passed to the dll
# function (and the yield returns the result of the call).
# It should then yield the result to be returned from the
# function call.
def decorate(func):
api = getattr(WinDLL( dllname), funcname)
api.restype = restype
api.argtypes = argtypes

def decorated(*args , **kw):
iterator = func(*args, **kw)
nargs = iterator.next()
if not isinstance(narg s, tuple):
nargs = (nargs,)
try:
res = api(*nargs)
except Exception, e:
return iterator.throw( e)
return iterator.send(r es)
return decorated
return decorate

from ctypes.wintypes import HWND #, RECT, POINT
LPARAM = c_ulong

class metaENUM(type(c types.c_int)):
def __init__(cls, name, bases, namespace):
'''Convert enumeration names into attributes'''
names = namespace.get(' _names_', {})
if hasattr(names, 'keys'):
for (k,v) in names.items():
setattr(cls, k, cls(v))
names[v]=k
else:
for (i,k) in enumerate(names ):
setattr(cls, k, cls(i))
super(metaENUM, cls).__init__(n ame, bases, namespace)

class ENUM(ctypes.c_i nt):
'''Enumeration base class. Set _names_ attribute to a list
of enumeration names (counting from 0)
or a dictionary of name:value pairs.'''
__metaclass__ = metaENUM
def __str__(self):
return self.__repr__(f mt="%(value)s" )

def __repr__(self, fmt="<%(name)s %(value)s>"):
try:
return self._names_[self.value]
except:
return fmt % dict(name=self. __class__.__nam e__, value=self.valu e)
def __int__(self):
return self.value

class BITMASK(ENUM):
'''Some Microsoft 'enums' are actually bitmasks with several bits or'd together'''
def __repr__(self, fmt="<%(name)s %(value)s>"):
v = self.value
values = []
while v:
bit = v&(~v+1)
try:
values.append(s elf._names_[bit])
except (KeyError, IndexError):
values.append(f mt % dict(name=self. __class__.__nam e__, value=self.valu e))
v &= ~bit
if not values:
return '0'
return '|'.join(values )
def __or__(self, other):
return type(self)(int( self.value)|int (other.value))

class SHOWCMD(ENUM):
_names_ = '''SW_HIDE SW_NORMAL SW_SHOW_MINIMIZ ED SW_SHOW_MAXIMIZ ED
SW_SHOW_NOACTIV ATE SW_SHOW SW_MINIMIZE SW_SHOWMINNOACT IVE
SW_SHOWNA SW_RESTORE SW_SHOWDEFAULT SW_FORCEMINIMIZ E'''.split()

class WindowPlacement Flags(BITMASK):
_names_ = dict(WPF_SETMIN POSITION = 1,
WPF_RESTORETOMA XIMIZED = 2,
WPF_ASYNCWINDOW PLACEMENT = 4)

class Structure(ctype s.Structure):
"""As ctypes Structure but with added repr and comparison testing"""
def __repr__(self):
return "%s(%s)" % (self.__class__ .__name__,
", ".join("%s= %r" % (f, getattr(self, f)) for (f,t) in self._fields_))
def __eq__(self, other):
if self._fields_ != other._fields_:
return False
for (f,t) in self._fields_:
if getattr(self,f) != getattr(other,f ):
return False
return True

class RECT(Structure) :
_fields_ = [("left", c_long),
("top", c_long),
("right", c_long),
("bottom", c_long)]

class POINT(Structure ):
_fields_ = [("x", c_long),
("y", c_long)]

class StructureWithLe ngth(Structure) :
_fields_ = [('length', ctypes.c_ulong)]
def __init__(self):
ctypes.Structur e.__init__(self )
self.length = ctypes.sizeof(s elf)

class WINDOWPLACEMENT (StructureWithL ength):
_fields_ = [
('flags', WindowPlacement Flags),
('showCmd', SHOWCMD),
('ptMinPosition ', POINT),
('ptMaxPosition ', POINT),
('rcNormalPosit ion', RECT),
]

def nonzero(result) :
# If the result is zero, and GetLastError() returns a non-zero
# error code, raise a WindowsError
if result == 0 and GetLastError():
raise WinError()
return result

WNDENUMPROC = ctypes.WINFUNCT YPE(ctypes.c_in t, HWND, LPARAM)
@ _stdcall("user3 2", c_int, "EnumWindow s", WNDENUMPROC, LPARAM)
def EnumWindows(cal lback, lparam=0):
yield nonzero((yield WNDENUMPROC(cal lback), lparam))

@ _stdcall("user3 2", c_int, "GetWindowTextL engthW", HWND)
def GetWindowTextLe ngth(hwnd):
yield nonzero((yield hwnd,))

@ _stdcall("user3 2", c_int, "GetWindowTextW ", HWND, c_wchar_p, c_int)
def GetWindowText(h wnd):
len = GetWindowTextLe ngth(hwnd)+1
buf = create_unicode_ buffer(len)
nonzero((yield hwnd, buf, len))
yield buf.value

@ _stdcall("user3 2", c_int, "GetClassNameW" , HWND, c_wchar_p, c_int)
def GetClassName(hw nd):
len = 256
buf = create_unicode_ buffer(len)
nonzero((yield hwnd, buf, len))
yield buf.value

@ _stdcall("user3 2", c_int, "GetWindowRect" , HWND, POINTER(RECT))
def GetWindowRect(h wnd):
buf = RECT()
nonzero((yield hwnd, buf))
yield buf

@ _stdcall("user3 2", c_int, "GetClientRect" , HWND, POINTER(RECT))
def GetClientRect(h wnd):
buf = RECT()
nonzero((yield hwnd, buf))
yield buf

@ _stdcall("user3 2", c_int, "GetWindowPlace ment", HWND, POINTER(WINDOWP LACEMENT))
def GetWindowPlacem ent(hwnd):
buf = WINDOWPLACEMENT ()
nonzero((yield hwnd, buf))
yield buf

@ _stdcall("user3 2", c_int, "SetWindowPlace ment", HWND, POINTER(WINDOWP LACEMENT))
def SetWindowPlacem ent(hwnd, placement):
yield nonzero((yield hwnd, placement))

@ _stdcall("user3 2", c_int, "IsWindow", HWND)
def IsWindow(hwnd):
yield bool((yield hwnd,))

@ _stdcall("user3 2", c_int, "ShowWindow ", HWND, SHOWCMD)
def ShowWindow(hwnd , showcmd):
yield bool((yield hwnd,showcmd))

def toplevelWindows ():
res = []
def callback(hwnd, arg):
res.append(hwnd )
return True
EnumWindows(cal lback, 0)
return res

def iterWindows(kla ss, match):
for hwnd in toplevelWindows ():
if IsWindow(hwnd):
try:
title = GetWindowText(h wnd)
except WindowsError, e:
continue
if klass==GetClass Name(hwnd) and match in title:
yield hwnd

if __name__=='__ma in__':
for hwnd in iterWindows("Mo zillaUIWindowCl ass", sys.argv[1]):
wp = GetWindowPlacem ent(hwnd)
ShowWindow(hwnd , SHOWCMD.SW_MINI MIZE)
else:
print "Sorry, I couldn't find the window"
-----------------------------------
May 16 '07 #4
Thanks guys, especially Duncan !

That's what I'm using now:

import sys
from win32gui import GetWindowText, EnumWindows, ShowWindow
from win32con import SW_MINIMIZE

def listWindowsHand les():
res = []
def callback(hwnd, arg):
res.append(hwnd )
EnumWindows(cal lback, 0)
return res

def listWindowsName s():
return (map(GetWindowT ext, listWindowsHand les()))

def minimizeWindow( ):
a_hwnd = listWindowsHand les()[listWindowsName s().index(sys.a rgv[1])]
ShowWindow(a_hw nd, SW_MINIMIZE)

minimizeWindow( )

May 17 '07 #5
Thanks guys, especially Duncan !

That's what I'm using now:

import sys
from win32gui import GetWindowText, EnumWindows, ShowWindow
from win32con import SW_MINIMIZE
def listWindowsHand les():
res = []
def callback(hwnd, arg):
res.append(hwnd )
EnumWindows(cal lback, 0)
return res

def listWindowsName s():
return (map(GetWindowT ext, listWindowsHand les()))

def minimizeWindow( ):
a_hwnd = listWindowsHand les()[listWindowsName s().index(sys.a rgv[1])]
ShowWindow(a_hw nd, SW_MINIMIZE)

minimizeWindow( )
May 17 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1387
by: Askari | last post by:
When I try to control a window (toplevel) with a thread (not the main thread), I can't set the 'visible' of the window with this example : app.state("withdrawn") In the main thread, I have no problem, but in other thread, the application freze. Note : I have no choice to put the "app.state("withdrawn")" in my thread and not in the main thread. Why, because it's for pop a window when the thread see a error and for query the user how do...
0
1158
by: ADavis | last post by:
We have an existing ActiveX control that plots data points over an image. When the mouse is moved over these points, a tool tip is supposed to be displayed indicating information about the point. This control is already deployed in an unmanaged application and works correctly there. We have been attempting to re-use it in a .Net forms based application and have gotten all other aspects to work except the tooltips. The ToolTips...
0
1528
by: Sergiu Dev | last post by:
I am working on a win forms application trying to control the DOM of a page that starts several javascript functions. I can control window.open() functions with the newwindow2() event of the AxWebBrowser control. However, I cannot seem to be able to control the DOM of a modal dialog window started by a javascript function using window.showModalDialog(). Any suggestions would be greatly appreciated.
8
5634
by: Dominic Tocci | last post by:
I'm searching for a way to use window.open on my web page to open a window in firefox that allows the sidebars to work (bookmarks, history, etc). When I use the following: var popWindow=window.open('http://www.yahoo.com','','width=600,height=400,toolbar=1,location=1,menubar=1,resizable=1,titlebar=1,directories=1,status=1,scrollbars=1'); the sidebars are disabled. I click on the buttons for bookmarks and history and they do nothing. I...
2
1531
by: roni | last post by:
hi. i want to build USER CONTROL that will be used in WEB PAGE. to build user control and use in web page,I KNOW . i did user control with textbox and lable for example and it works. the problem is after i had the IRC client functionality and Windows sockets it DID NOT work.
0
957
by: Neon genesis | last post by:
Well i'm try to use visual studio .net c# to build new interface with windows media player 10 in the backend but it seem like less architect and sample source code talk about it so i'm in blind now. So could any one can help me about some sample code or architec about this please send to me at eva10409@hotmail.com
6
1813
by: sck10 | last post by:
Hello, Can you control the window attributes (toolbar, scrollbars, left and right exc.) when using the hyperlink control as you would when using javascript? For examle, I am using the following javascript to open another window and would like to control these attributes with the hyperlink control: window.open(msgSubmitterInfo,t,s);return false" var s="toolbar=no,directories=no,scrollbars=yes,resizable=yes,"; s+= ...
2
4364
by: Tom Shelton | last post by:
I was goofing around tonight and decided to write a little IP address control. I had written a simple one a long time ago, but I decided I should try to write one that was half way correct :) Anyway, here is the result of about an hour and half of work... // IPControl.cs using System; using System.Collections; using System.ComponentModel; using System.Drawing;
0
1579
by: belalhaija | last post by:
I have read few articles about the TCP congestion window, AND when we are integrating wire and wireless networks some of the research use the chriteria of Bit error rate in wireless communications and try to study the effect that it has on the TCP congestion window, I find this as odd because there is the seperation of Layers on the internet model and the BER is in physical layer. I guess my question is can anybody explain to me if this is a...
5
4098
by: chosky | last post by:
Hello all experts, please, let me have your idea, my labtop turned to blacked-out screen it might be virus or else, I tried to repair this window vista still it show the welcome screen and then user account control dialog comes after I logon only the courser appear and the screen blacked out. if anyone who see this kind of problem and solve it, please give your support thanks anyway
0
8395
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8310
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8503
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8605
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7330
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6166
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4155
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4306
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.