win32gui get window content (internet explorer_server) - python

For the extraction of text from a chat window I started off by gathering the window handles.
I managed doing this by the following code:
import time, win32gui
def callback(hwnd, IEServers):
if win32gui.GetClassName(hwnd) == 'Internet Explorer_Server':
IEServers.append(hwnd)
print "IE server found:", hwnd
time.sleep(3)
mainHwnd = win32gui.GetForegroundWindow()
IEServers = []
win32gui.EnumChildWindows(mainHwnd, callback, IEServers)
for serv in IEServers:
print win32gui.GetClassName(serv)
Next thing I want to do is get the content (inner html?) as a string.
I believe it can be done via a IHTMLDocument2 object.
Info: http://support.microsoft.com/kb/q249232
How to do this?

You can try something like this. Maybe not exactly what you want but should get you on your way:
import time, win32gui
import win32com.client
time.sleep(2)
mainHwnd = win32gui.GetForegroundWindow()
s = win32com.client.Dispatch("Shell.Application")
for w in s.Windows():
if int(w.Hwnd) == mainHwnd:
print w.LocationURL
print w.Document.body.innerText
print w.Document.body.innerHTML
break
I think innerText is what you want, but I included several attributes so you can take your pick. This will only work with IE, of course.

Related

How Can I Print the Contents of my Tkinter Window to a Printer

I made an App to process and display some data in a Tkinter window. I now want to send the contents of the window to a printer for printing on actual paper. However I don't really see any libraries in tkinter or Python to do this. I have to confess I am very new to tkinter and Python.....
Can anyone point me in the right direction?
Thanks.
tkinter is for a graphics user interface and so is all about display. To print data in a tkinter widget you'd have to retrieve that data depending on what the widget is and put it on the clipboard (can do this in tkinter) or file it (in a separate function) and use a separate printing app to print.
(edited as per comment)
This code does much the same as the subprocess module in a minimalist fashion since you have a specific task on Windows. To test it needs a pdf filepath inserted so I've put in an example that brings up notepad just so it can run as it is.
This has an alternative to checking for print status by use of a manual pause. Then Adobe (or any executable that has the appropriate print facility) can be closed automatically. I'd expect the manual pause to be replaced by an automatic timer set for an estimate time for a document to print. Probably need to consider only the time needed to transfer the document into the printing buffer - but that is up to how you want to operate with your system.
"""Process to start external executable.
. default is to let process run until parent pause is complete then process is terminated in parent,
.. this allows time for a process started im the child like printing to finish.
. option to wait until process has finished before returning to parent.
(proc.py)
"""
import _winapi as win
from os import waitpid
from sys import exc_info as ei
def startproc(exe,cmd, wait=False):
try:
ph, th, pid, tid = win.CreateProcess(exe,cmd,None,None,1,0,None,None,None)
win.CloseHandle(th)
except:
print(ei()[1])
ph = 0
return (ph,'error')
if ph > 0:
if not wait:
return (ph,'process still going')
else:
pid, exitstatus = waitpid(ph,0)
return (0,'process done')
#exe = "C:\\Program Files\\Adobe\\Acrobat DC\\Acrobat\\Acrobat.exe"
#cmd = "open <pdf filepath>"
exe = "C:\Windows\System32\\notepad.exe"
cmd = None
print(__doc__)
proc,msg = startproc(exe,cmd)
print(msg)
if 'done' not in msg: # manual pause for printing
input('\n-- carry on --\n') # could be automatic timer
if msg != 'error' and proc != 0:
if win.GetExitCodeProcess(proc) == win.STILL_ACTIVE:
win.TerminateProcess(proc,0)
if 'done' not in msg: print('process closed')
#can delete pdf here
input('\n--- finish ---\n')

Click event for a notification in python with Plyer

while(True):
plyer.notification.notify(
title = title,
message = message,
app_icon = icon,
timeout = 50
)
time.sleep(3600)
I want to be able to access a link when the notification is clicked. I have not found anything like a click event in the source code. I was thinking that maybe it could be called when the timeout is 0 or something similar. If there is another way of doing it without plyer it could also work for me, but I have not found anything. Thanks in advance.
Try win10toast-click. It is not in-built so you have to pip install it.
You can use
from win10toast_click import ToastNotifier
to import it
You can use it by typing
toaster = ToastNotifier() toaster.show_toast(title=,message=,icon_path=,duration=,threaded=True,callback_on_click=yourfunction )
after that you could use webbrowser module to create your function to open the link

Python Pyautogui: Why doesn't he right click in my code?

I have made a script that checks 100 times whether an image can be detected. He clicks it if it is seen in the last if statement. But a few things are going wrong here.
1: He doesn't right-click what I do.
2: after clicking my script closes immediately!
What did I do wrong? and how do I fix this?
This is my code
import os
import pyautogui
import time
import subprocess
def openprogram():
#opens program
subprocess.call(["cmd", "/c", "start", "/max", "D:\FarmHelper3.exe"])
def inloggen():
#searches for image 100 times to login
for _ in range(100):
time.sleep(1)
coords = pyautogui.locateOnScreen('images/login.png')
#if he has not found the photo within the program
if coords == None:
print ("Geen login gevonden")
#if the picture is found
if coords != None:
print ("Login gevonden")
pyautogui.rightClick(coords)
openprogram()
inloggen()

Excel button click event in Python

I was using pywin32 to make a connection between Python and Excel and I was starting to deal with events. It happens that in the project I'm working with, I would need to capture a button click event in Python. I've seen events from Workbooks and Worksheets, but I can't figure out the click ones.
class WorkbookEvents:
def OnSheetSelectionChange(self, *args):
#print(args)
print("You changed the selection")
#print(args[1].Address)
#args[0].Range("A1").Value = "Range :" + str(args[1].Address)
workbook_events= WIN32.WithEvents(wb, WorkbookEvents)
quite late for an answer but I got it working with this piece of code (and using the ActiveX "Command Button" control in Excel)
import win32com.client as win32
import pythoncom
import sys
import time
#The event handlers container
class wsEvents:
def OnClick(self,*args):
print('Button Clicked')
xlApp = win32.Dispatch("Excel.Application")
xlwb = xlApp.Workbooks("Book1.xlsm")
ws=xlwb.Sheets("Sheet1")
xl_events=win32.WithEvents(ws.OLEObjects("CommandButton1").Object,wsEvents)
# define initalizer
keepOpen = True
while keepOpen:
time.sleep(0.1)
# display the message
pythoncom.PumpWaitingMessages()
try:
# if the workbook count does not equal zero we can assume Excel is open
if xlApp.Workbooks.Count != 0:
keepOpen = True
# otherwise close the application and exit the script
else:
keepOpen = False
xlApp = None
sys.exit()
except:
# if there is an error close excel and exit the script
keepOpen = False
xl = None
The ActiveX command button is loaded in Excel as an "independent" COM(OLE) object that is referenced by the worksheet where it is displayed. The Excel API permit to get a reference to OLE objects as explained here and easily done in python code.
Basically the event handlers are not managed by the worksheet but by the Command Button object instead, and of course the events supported by a Command Button are OnClick etc...Turns out that the solution is elegant and that win32com has much respect for COM :)
Credits must be given to Alex Reed blog about his snippet to keep python script waiting for new events.

Get the name of a window using Windows API

I am new to python and I am trying to write a script that exits out of a loop when a certain window closes. I am having problems getting the code to work properly it won't even enter the loop. I think this is because I am not properly getting the window name. I was wondering if there are any good tutorials on the Win32Gui extension that would help me to understand how it works.
Edit
Here is what I have, it is doing what it is suppose to do, but I am sure there is an easier way of doing it.
def answerCalls(local, network):
t = 0
count = 0
while t == 0:
time.sleep(1)
if win32gui.GetWindowText(win32gui.GetForegroundWindow()) == "Incoming Call":
time.sleep(10)
getApplicationPos("Incoming Call")
clickOnElement(******.IncomingCall_AnswerButton())
time.sleep(10)
if win32gui.GetWindowText(win32gui.GetForegroundWindow()) == "Video Call":
count += 1
writeFile("Answering Calls", count, local)
uploadToServer(local, network)
The following example (Python 3) gets a list of the titles of all the windows:
import win32gui
def enum_window_titles():
def callback(handle, data):
titles.append(win32gui.GetWindowText(handle))
titles = []
win32gui.EnumWindows(callback, None)
return titles
titles = enum_window_titles()

Categories