How do I open a minimized window using python? - python

is it possible to un-minimize a minimized window using python on windows 10? (I'm using python 3.8)
I would add more detail but that's really all I need to say.

I combined information from multiple sources and got this to work (Miniconda Python 3.6, Windows 10)
import win32gui
import win32con
def windowEnumHandler(hwnd, top_windows):
top_windows.append((hwnd, win32gui.GetWindowText(hwnd)))
def bringToFront(window_name):
top_windows = []
win32gui.EnumWindows(windowEnumHandler, top_windows)
for i in top_windows:
# print(i[1])
if window_name.lower() in i[1].lower():
# print("found", window_name)
win32gui.ShowWindow(i[0], win32con.SW_SHOWNORMAL)
win32gui.SetForegroundWindow(i[0])
break
# Test with notepad
if __name__ == "__main__":
winname = "notepad"
bringToFront(winname)
The Handler is not optimal; it spits out various processes that are not the windows in the taskbar. However, as long as your window_name is specific I don't think you'll run into problems. If you remove the break, all matches will be "opened".
Sources: Mouse and Python Blog
Another StackOverflow question

Related

GUI Interface For Command Line Input/Output

I was hoping somebody could point me in the right direction for a project I would like to do. My intention is simple, to have a GUI that allows a user to input a string, that string fills into a pre-determined line of command line text, runs through the command line and returns what is printed on the command line screen. I've been leaning toward using Python for this but I am still not sure about the syntax that will accomplish even the first part, where a user will input a string and that string will run through the line of command line text. Any sort of input would be greatly appreciated!
This is a simple GUI using tkinter for python
try:
import tkinter as tk # python v3
except:
import Tkinter as tk # python v2
# This function is called when the submit button is clicked
def submit_callback(input_entry):
print("User entered : " + input_entry.get())
return None
####################### GUI ###########################
root = tk.Tk()
root.geometry('300x150') #Set window size
# Heading
heading = tk.Label(root, text="A simple GUI")
heading.place(x = 100, y = 0)
input_label = tk.Label(root, text="Enter some text")
input_label.place(x = 0, y = 50)
input_entry = tk.Entry(root)
input_entry.place(x = 100, y = 50)
submit_button = tk.Button(root, text = "Submit", command = lambda: submit_callback(input_entry))
submit_button.place(x = 200, y = 90)
root.mainloop()
#############################################################
Developing a GUI is a big project for python beginners, there are several possibilities to do this. If you want to seriously develop GUI applications in Python I would recommend you to try Qt4 or Qt5 via pyside or pyqt. You may need one or more tutorials and maybe some problems to get your first working GUI applications, but you will be able to build any kind of professional cross-platform applications using this libraries.
With running command line text, you mean system commands or python commands? If you want to run system commands, I would recommend you to write a short python script, that handles user input (within the python commandline) and passes it to the system using subprocess (from subprocess import call).
If you have done your first simple textform in pyqt and the script that handles user input try to connect them by wrapping the Qt application around the commandline script. If you just looking for a quick and dirty solution there are several libraries, that support some easy to setup GUI frames or webinterfaces (to run in the browser on the local machine). But if you are a programming beginner I would highly recommend to split this into twor or three minor projects, to keep the frustration level low ;).
Edit Python2 vs Python3: pyqt and pyside are available for both python2 and python3 (as the most, but not all libraries) so your choice between py2 and py3 is on your own. The Syntax is almost the same (except the print() command), but the libraries you install are only working in the version you installed them.
If you are working on a linux machine you can easily install both versions in parallel if you want to make sure the right version is called you can specify the command such as python2 or python3 instead of running the default with python
Edit2 handle user input:
from subprocess import check_output
def predefined_command(user_input):
command = ['net', 'user', '/domain', user_input]
answer = check_output(command, args)
decoded = answer.decode('utf8')
return answer

PySDL2: Creating a borderless window

I've been trying to find how I might create a borderless window (One not created using the typical windows border) in PySDL2.
I've looked at what resources I could find online, but haven't been able to pinpoint anything that would tell me how to accomplish this, despite it being apparently possible.
Research:
This link states that in most cases you have a border and title bar around your window, but never went into any more detail as to how to manipulate it.
I looked at some API references for SDL's Window, and did not see that borders could be manipulated at all. (Not stated that they couldn't be, just no mention)
Despite not finding anything PySDL2 related, I did find at this link that:
sdl.setWindowBordered(window, bordered)
Sets the border state of a window.
Unfortunately, I'm unable to get this to work within my simple example script.
Thanks for looking!
You need to make sure you have the flag: SDL_WINDOW_BORDERLESS.
Full example:
import sys
import sdl2.ext
sdl2.ext.init()
window = sdl2.ext.Window("Hello World!", size=(640, 480), flags=sdl2.SDL_WINDOW_BORDERLESS)
window.show()
processor = sdl2.ext.TestEventProcessor()
processor.run(window)
Modifying your script slightly we get:
import sys
import sdl2.ext
def run():
sdl2.ext.init()
W = sdl2.ext.Window("Default",size=(400,300), flags=sdl2.SDL_WINDOW_BORDERLESS)
W.show()
running = True
while running:
events = sdl2.ext.get_events()
for event in events:
if event.type == sdl2.SDL_QUIT:
running = False
break
W.refresh()
return 0
if __name__ == "__main__":
sys.exit(run())

how to get running program in windows xp taskbar in python?

I've use this code to get the top level windows. Is there a way to get only running program in the taskbar? Sorry for the format. Thanks
def windowEnumerationHandler(hwnd, resultList):
'''Pass to win32gui.EnumWindows() to generate list of window handle, window text tuples.'''
resultList.append((hwnd, win32gui.GetWindowText(hwnd)))
topWindows = []
win32gui.EnumWindows(windowEnumerationHandler, topWindows)

Python console prints output differently than sypder console

I have a python code that takes measurements off of a HP LCR Meter and collects the data for us in various ways. I recently created a GUI for imputing initial conditions for employees not comfortable modifying variables in the code. Everything works except for 1 thing. WE use the latest python xy so python version 2.6.6 with pyqt and spyder on a windows 7 PC.
Normally we would open the code in spyder. But opening spyder takes a while and my supervisor liked the ability to just double click on the file which opens the GUI with a python console window to print errors and various information as you would see in spyder.
As can be seen in the screen shots provided, there is a initial machine setup mode for setting up the device to be scanned by the LCR Meter and there are two user inputs that the code prompts. On spyder it prints these prompts nicely in the console but in the python console opened without spyder it continuously prints QCoreApplication::exec: The event loop is already running Weird thing is you can still just push enter twice as normal and the code will run like normal. But its going to be confusing to basically everyone but me.
Does anyone know why this would be happening?
Here are the pictures of the output
Here is the code that prompts the input.
lcr = visa.instrument('GPIB::17')
#clear the instrument
lcr.write('*RST;*CLS')
#enable operation complete notification
lcr.write('*OPC')
if parallel:
lcr.write('FUNC:IMP CPG') #Parallel capacitance, conductance model
else:
lcr.write('FUNC:IMP CSRS') #Series capacitance, resistance model
lcr.write('APER '+integration+','+averages)
lcr.write('OUTP:HPOW ON')
lcr.write('OUTP:DC:ISOL OFF')
lcr.write('VOLT '+vac)
lcr.write('TRIG:SOUR BUS')
if zero == True:
#set open correction parameters
lcr.write('DISP:PAGE CSET')
lcr.write('CORR:LENG 1')
lcr.write('CORR:METH SING')
lcr.write('CORR:LOAD CPG')
lcr.write('CORR:USE 10')
lcr.write('CORR:SPOT1:STATE ON')
lcr.write('CORR:SPOT2:STATE OFF')
lcr.write('CORR:SPOT3:STATE OFF')
lcr.write('CORR:SPOT1:FREQ '+frequency)
#perform open correction -> unprobe device\
raw_input('Unprobe DUT and press ENTER to continue...')
lcr.write('CORR:SPOT1:OPEN')
lcr.write('CORR:OPEN:STATE ON')
lcr.write('DISP:PAGE MEAS')
#poll lcr to determine measurment state
lcr.write('*OPC?')
done = lcr.read()
while done == 0:
lcr.write('*OPC?')
done = lcr.read()
time.sleep(0.5)
#reprobe device
raw_input('Probe DUT, then press ENTER')
lcr.write('FREQ '+frequency)
The Prompts are the two raw_input().
Reason why you get continuous messages in your console, is that system logs use same output-stream than your app.
Spyder is nice program, which just embeds IPython or Python(backup) console in QT window, you can use similar solution - just use Qt4 to draw window, which includes IPython console
What you need to do is this(source):
def embed_ipython(window):
"wrapper funcs - works < IPython 0.11"
from IPython.Shell import IPShellEmbed
ipshell = IPShellEmbed(user_ns = dict(w = window))
ipshell()
Here ‘window’ is a central object of some kind that you want to expose to IPython (to manipulate, test various methods, etc).
GUI app initialization would be like this:
if __name__ == "__main__":
import sys
from PyQt4 import QtGui
app = QtGui.QApplication(sys.argv)
window = QtGui.QMainWindow()
window.show()
embed_ipython(window)
sys.exit(app.exec_())
Some additional readings:
QT4 tutorial: http://zetcode.com/tutorials/pyqt4/firstprograms/
Similar topic - how to embed python console: How to embed a Python interpreter in a PyQT widget
IPython and QT console: http://ipython.org/ipython-doc/dev/interactive/qtconsole.html

How do I take out the focus or minimize a window with Python?

I need to get focus to a specified window, and the only way I'm seeing on my head, is minimizing all windows on front of it until I get the right one...
How can I do it?
Windows 7, and no specific toolkit....
Every type of window, for example, firefox and console command
You'll need to enumerate through the windows and match the title of the window to get the one you want. The code below searches for a window with "firefox" in the title and sets the focus:
import win32gui
toplist = []
winlist = []
def enum_callback(hwnd, results):
winlist.append((hwnd, win32gui.GetWindowText(hwnd)))
win32gui.EnumWindows(enum_callback, toplist)
firefox = [(hwnd, title) for hwnd, title in winlist if 'firefox' in title.lower()]
# just grab the first window that matches
firefox = firefox[0]
# use the window handle to set focus
win32gui.SetForegroundWindow(firefox[0])
To minimize the window, the following line:
import win32con
win32gui.ShowWindow(firefox[0], win32con.SW_MINIMIZE)
You'll need to enumerate through the windows and match the title of the window to get the one you want. The code below searches for a window with "firefox" in the title and sets the focus
To minimize the window use the following line:
def enumHandler(hwnd, lParam):
if 'firefox' in win32gui.GetWindowText(hwnd):
win32gui.ShowWindow(hwnd, win32con.SW_MINIMIZE)
win32gui.EnumWindows(enumHandler, None)
This works for Windows 10, Python3.5 32bit, pywin32‑223.
I reported the above case, but an error occurred.
Traceback (most recent call last):
TypeError: The object is not a PyHANDLE object
I'm assuming from the question, that you want to write a generic to that can work with any window from any application.
You might want to try the Python Win32 GUI Automation library. I haven't used it but sounds like it might be what you are looking for. If that doesn't work, your best option might be forgo python and use a tool like AutoIt that provides built in support for window manipulation.
If neither of those solutions work you will probable have to directly invoke windows api. I do not know if the win32api package wraps the necessary functionality, otherwise you will have write a python module in c/c++.
If this kind of functionality is available in the .net api, you could use IronPython.

Categories