I'm very new to python and I'm trying to print the url of an open websitein Chrome. Here is what I could gather from this page and googeling a bit:
import win32gui, win32con
def getWindowText(hwnd):
buf_size = 1 + win32gui.SendMessage(hwnd, win32con.WM_GETTEXTLENGTH, 0, 0)
buf = win32gui.PyMakeBuffer(buf_size)
win32gui.SendMessage(hwnd, win32con.WM_GETTEXT, buf_size, buf)
return str(buf)
hwnd = win32gui.FindWindow(None, "Chrome_WidgetWin_1" )
omniboxHwnd = win32gui.FindWindowEx(hwnd, 0, 'Chrome_OmniboxView', None)
print(getWindowText(hwnd))
I get this as a result:
<memory at 0x00CA37A0>
I don't really know what goes wrong, whether he gets into the window and the way I try to print it is wrong or whether he just doesn't get into the window at all.
Thanks for the help
Only through win32 can only get the information of the top-level application. If you want to get the information of each component located in the application, you can use UI Automation.
Python has a wrapper package Python-UIAutomation-for-Windows, and then you can get the browser's address bar url through the following code:
import uiautomation as auto
def get_browser_tab_url(browser: str):
"""
Get browser tab url, browser must already open
:param browser: Support 'Edge' 'Google Chrome' and other Chromium engine browsers
:return: Current tab url
"""
if browser.lower() == 'edge':
addr_bar = auto.EditControl(AutomationId='addressEditBox')
else:
win = auto.PaneControl(Depth=1, ClassName='Chrome_WidgetWin_1', SubName=browser)
temp = win.PaneControl(Depth=1, Name=browser).GetChildren()[1].GetChildren()[0]
for bar in temp.GetChildren():
last = bar.GetLastChildControl()
if last and last.Name != '':
break
addr_bar = bar.GroupControl(Depth=1, Name='').EditControl()
url = addr_bar.GetValuePattern().Value
return url
print(get_browser_tab_url('Edge'))
print(get_browser_tab_url('Google Chrome'))
print(get_browser_tab_url('Cent Browser'))
This should work:
import uiautomation as auto
control = auto.GetFocusedControl()
controlList = []
while control:
controlList.insert(0, control)
control = control.GetParentControl()
control = controlList[0 if len(controlList) == 1 else 1]
address_control = auto.FindControl(control, lambda c, d:
isinstance(c, auto.EditControl))
print('Current URL:')
print(address_control.GetValuePattern().Value)
Related
I try to read values from fields of a window dialog.
In the dialog configuration I have this:
#define IDC_SYMBOL 8011
#define IDC_SHARES 8012
dialog snapshot picture
this is my simple code tried:
import win32gui,win32con
wT="my_dialog"
dlg=win32gui.FindWindow(None,wT)
d1=win32gui.GetDlgItem(dlg, 8011)
d2=win32gui.GetDlgItem(dlg, 8012)
print('d1: ', d1)
print('d2: ', d2)
def dumpWindow(hwnd, wantedText=None, wantedClass=None):
windows = []
hwndChild = None
while True:
hwndChild = win32gui.FindWindowEx(hwnd, hwndChild, wantedClass, wantedText)
if hwndChild:
textName = win32gui.GetWindowText(hwndChild)
className = win32gui.GetClassName(hwndChild)
windows.append((hwndChild, textName, className))
else:
return windows
windows = dumpWindow(dlg, wantedText='Symbol')
print(windows)
And this is what I get when running it:
d1: 1051340
d2: 920324
[(9112016, 'Symbol', 'Static')]
How do I read the actual values in those window dialog fields?
I also tried to get the dialog item text:
dText=win32gui.GetDlgItemText(dlg, 8011)
print('dText: ', dText)
and result is empty while the expected result is 'AAPL' for example, or whatever is there.
dText:
Why you don't use GetDlgItemText.
Normally, this function will return the text of a dialog control
Solution:
from sys import exit
import win32gui,win32con
wT="my_dialog"
dlg=win32gui.FindWindow(None,wT)
d1=win32gui.GetDlgItem(dlg, 8011) #symbol
def getEditText(hwnd):
buffer = win32gui.PyMakeBuffer(255)
bufLen = win32gui.SendMessage(hwnd, win32con.WM_GETTEXTLENGTH, 255, buffer)
win32gui.SendMessage(hwnd, win32con.WM_GETTEXT, 255, buffer)
text = buffer[0:bufLen*2]
return text
print ('Symbol: ', str(getEditText(d1),'utf-16'))
this script prints the selected symbol:
Symbol: ZVZZT
We have an old, legacy database that needs input from another system. SendInput method of data input into database forms is slow and unreliable, setting clipboard and then ^v is not reliable either (I have no idea why, but database interface is very old, early 2000s). After a lot of fiddling I discovered that using SendMessage to set text and then sending VK_RETURN is fast (much faster than SendInput/keybd_event) and reliable with our database. Now this code in plain C works:
HWND fghwnd = GetForegroundWindow();
DWORD threadId = GetWindowThreadProcessId(fghwnd, NULL);
DWORD myId = GetCurrentThreadId();
if (AttachThreadInput(myId, threadId, true)) {
HWND ctrl = GetFocus();
SendMessage(ctrl, WM_SETTEXT, 0, (LPARAM) sendbuf); // TESTING
PostMessage(ctrl, WM_KEYDOWN, VK_RETURN, 0);
PostMessage(ctrl, WM_KEYUP, VK_RETURN, 0);
AttachThreadInput(myId, threadId, false);
} else {
printf("\nError: AttachThreadInput failure!\n");
}
But this one in python does not:
foregroundHwnd = win32gui.GetForegroundWindow()
foregroundThreadID = win32process.GetWindowThreadProcessId(foregroundHwnd)[0]
ourThreadID = win32api.GetCurrentThreadId()
if foregroundThreadID != ourThreadID:
win32process.AttachThreadInput(foregroundThreadID, ourThreadID, True)
focus_whd = win32gui.GetFocus()
win32gui.SendMessage(focus_whd, win32con.WM_SETTEXT, None, "test text")
win32gui.PostMessage(focus_whd, win32con.WM_KEYDOWN, win32con.VK_RETURN, None)
win32gui.PostMessage(focus_whd, win32con.WM_KEYUP, win32con.VK_RETURN, None)
win32process.AttachThreadInput(foregroundThreadID, ourThreadID, False)
The trouble is, most of our new logic in python. I turned that C code into a small python module and it works, but as result now I've got dependency on Microsoft's huge compiler and a lot of fiddling with module building. I'd like to have a python-only solution.
Any ideas why this python code does not work? These system calls look the same...
Yes, AttachThreadInput failed. According to the comment here https://toster.ru/q/79336 win32process.GetWindowThreadProcessId returns wrong value, ctypes must be used. This code works:
"""
Fast "paste" implemented via calls to Windows internals, sends parameter
string and RETURN after that
Usage:
from paste import paste
paste("test")
"""
import time
import random
import string
from ctypes import windll
import ctypes
import win32con
def random_string(string_length=10):
"""Generate a random string of fixed length """
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(string_length))
ERROR_INVALID_PARAMETER = 87
def paste(text_to_paste):
"""Fast "paste" using WM_SETTEXT method + Enter key"""
current_hwnd = windll.user32.GetForegroundWindow()
current_thread_id = windll.kernel32.GetCurrentThreadId()
thread_process_id = windll.user32.GetWindowThreadProcessId(current_hwnd, None)
if thread_process_id != current_thread_id:
res = windll.user32.AttachThreadInput(thread_process_id, current_thread_id, True)
# ERROR_INVALID_PARAMETER means that the two threads are already attached.
if res == 0 and ctypes.GetLastError() != ERROR_INVALID_PARAMETER:
print("WARN: could not attach thread input to thread {0} ({1})"
.format(thread_process_id, ctypes.GetLastError()))
return
focus_whd = windll.user32.GetFocus()
windll.user32.SendMessageW(focus_whd, win32con.WM_SETTEXT, None, text_to_paste)
windll.user32.PostMessageW(focus_whd, win32con.WM_KEYDOWN, win32con.VK_RETURN, None)
windll.user32.PostMessageW(focus_whd, win32con.WM_KEYUP, win32con.VK_RETURN, None)
res = windll.user32.AttachThreadInput(thread_process_id, current_thread_id, True)
if __name__ == '__main__':
time.sleep(5) # time to switch to the target
# paste random 150 char string
paste(random_string(150))
I'm trying to save a website as PDF through printing dialog. My code allows me to save as pdf, but asks me to input a filename, which I don't know how to pass a filename to the pop up box.
Attached is my code:
import time
from selenium import webdriver
import os
class printing_browser(object):
def __init__(self):
self.profile = webdriver.FirefoxProfile()
self.profile.set_preference("services.sync.prefs.sync.browser.download.manager.showWhenStarting", False)
self.profile.set_preference("pdfjs.disabled", True)
self.profile.set_preference("print.always_print_silent", True)
self.profile.set_preference("print.show_print_progress", False)
self.profile.set_preference("browser.download.show_plugins_in_list",False)
foxdriver = r'C:\Users\AShen\Documents\Workspace\geckodriver.exe'
self.driver = webdriver.Firefox(executable_path=foxdriver,firefox_profile = self.profile)
time.sleep(5)
def get_page_and_print(self, page):
self.driver.get(page)
time.sleep(5)
self.driver.execute_script("window.print();")
if __name__ == "__main__":
browser_that_prints = printing_browser()
browser_that_prints.get_page_and_print('http://www.google.com/')
These days I had the same question.
I solved it without using the pyautogui in these case, because I use different PCs and monitors and I didn't want to depend on the position of the click.
I was able to solve it using the about:config... changing them with each necessary print (in PDF).
The name of my printer "in PDF" in Ubuntu is "Print to File" (defined in print_printer) and the settings of about:config need to be this printer...
For example: print.printer_Print_to_File.print_to_file: true
import os
import time
from selenium import webdriver
class printing_browser(object):
def __init__(self):
self.profile = webdriver.FirefoxProfile()
self.profile.set_preference('services.sync.prefs.sync.browser.download.manager.showWhenStarting', False)
self.profile.set_preference('pdfjs.disabled', True)
self.profile.set_preference('print.always_print_silent', True)
self.profile.set_preference('print.show_print_progress', False)
self.profile.set_preference('browser.download.show_plugins_in_list', False)
self.profile.set_preference('browser.download.folderList', 2)
self.profile.set_preference('browser.download.dir', '')
self.profile.set_preference('browser.download.manager.showWhenStarting', False)
self.profile.set_preference('browser.aboutConfig.showWarning', False)
self.profile.set_preference('print.print_headerright', '')
self.profile.set_preference('print.print_headercenter', '')
self.profile.set_preference('print.print_headerleft', '')
self.profile.set_preference('print.print_footerright', '')
self.profile.set_preference('print.print_footercenter', '')
self.profile.set_preference('print.print_footerleft', '')
self.profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'application/octet-stream;application/vnd.ms-excel;text/html')
foxdriver = r'C:\Users\AShen\Documents\Workspace\geckodriver.exe'
self.driver = webdriver.Firefox(
executable_path=foxdriver,
firefox_profile=self.profile
)
time.sleep(1)
def get_page_and_print(self, page, filepath):
# Get about:config
self.driver.get('about:config')
time.sleep(1)
# Define Configurations
script = """
var prefs = Components.classes['#mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
prefs.setBoolPref('print.always_print_silent', true);
prefs.setCharPref('print_printer', 'Print to File');
prefs.setBoolPref('print.printer_Print_to_File.print_to_file', true);
prefs.setCharPref('print.printer_Print_to_File.print_to_filename', '{}');
prefs.setBoolPref('print.printer_Print_to_File.show_print_progress', true);
""".format(filepath)
# Set Configurations
self.driver.execute_script(script)
time.sleep(1)
# Get site to print in pdf
self.driver.get(page)
time.sleep(2)
self.driver.execute_script("window.print();")
browser_that_prints = printing_browser()
browser_that_prints.get_page_and_print('http://www.google.com', os.path.join(os.getcwd(), 'mywebpage.pdf'))
Oh, it is very easy if you know about pyautogui.
This is an amazing module that allows you to automate your curser.
So essentially, you need to figure out the place where the popup appears and use pyautogui to click it for you.
All you need to add is:
time.sleep(3)
i=random.randint(0,1000)
file_name=('name_pdf '+str(i))
print (file_name)
pyautogui.typewrite(file_name)
pyautogui.click(512,449)
Entire code structure will look like this:
import time
import pyautogui
from selenium import webdriver
import os
class printing_browser(object):
def __init__(self):
self.profile = webdriver.FirefoxProfile()
self.profile.set_preference("services.sync.prefs.sync.browser.download.manager.showWhenStarting", False)
self.profile.set_preference("pdfjs.disabled", True)
self.profile.set_preference("print.always_print_silent", True)
self.profile.set_preference("print.show_print_progress", False)
self.profile.set_preference("browser.download.show_plugins_in_list",False)
foxdriver = r'C:\Users\Pranjal Pathak\Desktop\Titanic Kaggle\geckodriver.exe'
self.driver = webdriver.Firefox(executable_path=foxdriver,firefox_profile = self.profile)
time.sleep(5)
def get_page_and_print(self, page):
self.driver.get(page)
time.sleep(5)
self.driver.execute_script("window.print();")
if __name__ == "__main__":
browser_that_prints = printing_browser()
browser_that_prints.get_page_and_print('http://www.python.org/')
time.sleep(3)
i=random.randint(0,1000)
file_name=('name_pdf '+str(i))
print (file_name)
pyautogui.typewrite(file_name)
pyautogui.click(512,449)
Note: 1. I have selected the name of the file as name+any random integer between 1 to 1000 to change name every time you save the file. This way it will save every time you run the code as the names will be different every time.
If this types the name but does not save the file, you might want to change the coordinates of your curser. Let me know if that happens.
I am doing a project and I want him to be invisible. Therefore, i used this website - http://pytoexe.com/ to create an window based exe file from my python script which means it will not use the windows console.
Unfortuently, since i am using phantomjs driver in my code, he opens a phantomjs console which interrupt me.
In order to slove this problem I need to add a line or script that prevent from the phantomjs console to appear ( changing something in my selenium files/ something like that would not work cause it probably problem in their files and i cannot doing anything with that) .
Someone know what to do?
this is my exe file
and This is my code:
from selenium import webdriver
import time
from PIL import Image
from constants import *
import operator
import os
#Email Constants
DEFAULT_CONTENT = 'example email stuff here'
HOST = 'smtp.gmail.com'
PORT = 587
EMAIL = 'freeadsandspam#gmail.com'
CUSTOMERS = []
SUBJECTS = ['new ad were found', 'ad were found by SMADS', 'best ad for you']
COMMASPACE = ', '
#Getting History
OUTPUT_FILE_PATH = 'C:\search_logger.txt'
COPY_OF_THE_HISTORY_PATH = 'C:\history'
NEW_OUTPUT_FILE_PATH = 'C:\last_search_logger.txt'
#PhantomJs And Ads Finding
PHANTOM_JS_PATH = 'C:\phantomjs-2.1.1-windows\\bin\phantomjs.exe'
OUTPUT_AD_PATH = 'ad.png'
DEFAULT_WINDOW_SIZE = (1024, 768)
AD_DATABASE = 'https://www.findads.com.au/'
KEYWORD_BUTTON_XPATH = '//*[#id="txtSearch"]'
SEARCH_BUTTON_XPATH = '/html/body/div[1]/div/form/button'
CONSTANT_TIME_SLEEPING = 3
AD_XPATH = '/html/body/div[1]/section/div/div[1]/div[4]/div[1]/div[1]/section[24]'
COMPARE_ELEMENT_XPATH = '//*[#id="fSearch"]'
CATAGORY_SORT_XPATH = '/html/body/div[1]/section/div/div[1]/div[5]/div/div[3]/form/div[1]/div[1]'
class PhantomJsDriver:
"""
A class that taking care on the ads finding
in the internet, doing it with PhantomJs -
background driver
"""
def __init__(self, ad_keyword, window_size=DEFAULT_WINDOW_SIZE, panthom_js_path=PHANTOM_JS_PATH, output_ad_path=OUTPUT_AD_PATH):
"""
this function init our object
in order to use the other functions
that the object offer.
Parameters
----------
phantom_js_path : str
path of the PhantomJs ( this essential because
we cannot get the PhantomJs file otherwise)
output_ad_path : str
where you want to save the ad that the system
had found and how you call the name of the ad
file ( eg: ad.png )
ad_keyword : str
the keyword that define what ad the system bring
( eg: dog will bring dog ad )
window_size : double int (int1,int2)
define the window size of the browser ( mainly for the
screenshot )
"""
self.phantom_js_path = panthom_js_path
self.output_ad_path = output_ad_path
self.ad_keyword = ad_keyword
self.window_size = window_size
self.list_of_images = []
self.dict = {}
def get_ad(self):
"""
this function save the ad by searching in the internet
( on specific website ) the keyword that the user chose
and copy it into the output_ad_path.
"""
for i in range(0, 5):
driver = webdriver.PhantomJS(self.phantom_js_path)
driver.set_window_size(self.window_size[0], self.window_size[1])
driver.get(AD_DATABASE)
keyword = driver.find_element_by_xpath(KEYWORD_BUTTON_XPATH)
keyword.send_keys(self.ad_keyword)
search_button = driver.find_element_by_xpath(SEARCH_BUTTON_XPATH)
search_button.click()
driver.save_screenshot("ad" + str(i) + ".png")
element = driver.find_element_by_xpath(AD_XPATH) # find part of the page you want image of
self.crop_image(i, element)
def crop_image(self, i, element):
"""
this function crop the screenshot of the ads website from
the previous function into one single ad.
"""
im = Image.open("ad" + str(i) + ".png") # uses PIL library to open image in memory
location = element.location
size = element.size
left = location['x']
top = location['y']
right = location['x'] + size['width'] + 50
bottom = location['y'] + size['height']
weight, height = im.size
print height
im = im.crop((left, top, right, bottom)) # defines crop points
im.save('test' + str(i) + '.png') # saves new cropped image
self.list_of_images.append('test' + str(i) + '.png')
self.dict['test' + str(i) + '.png'] = 0
def choose_the_best_ad(self):
for img1 in self.list_of_images:
for img2 in self.list_of_images:
im1 = Image.open(img1)
im2 = Image.open(img2)
if list(im1.getdata()) == list(im2.getdata()):
self.dict[img1] += 1
self.dict[img2] += 1
print self.dict
BestImage = max(self.dict.iteritems(), key=operator.itemgetter(1))[0]
print BestImage
if os.path.exists("TheImage.png"):
os.remove("TheImage.png")
os.rename(BestImage, "TheImage.png")
driver = PhantomJsDriver("dog")
driver.get_ad()
driver.choose_the_best_ad()
I am trying to do this in Python 2.7. I have found an answer for it in C# here, but I am having trouble recreating it in Python. The answer suggested here does explain the concept which I understand, but I have no idea how to get it going.
Basically I just want to mark a file, press Winkey+C and have its path copied. I know how to do the hotkey part (pyhk, win32 [RegisterHotKey]), but my trouble is working around with the filepath.
Thanks in advance!
it takes a lot of hacking around, but a rough solution is below:
#!python3
import win32gui, time
from win32con import PAGE_READWRITE, MEM_COMMIT, MEM_RESERVE, MEM_RELEASE, PROCESS_ALL_ACCESS, WM_GETTEXTLENGTH, WM_GETTEXT
from commctrl import LVM_GETITEMTEXT, LVM_GETITEMCOUNT, LVM_GETNEXTITEM, LVNI_SELECTED
import os
import struct
import ctypes
import win32api
GetWindowThreadProcessId = ctypes.windll.user32.GetWindowThreadProcessId
VirtualAllocEx = ctypes.windll.kernel32.VirtualAllocEx
VirtualFreeEx = ctypes.windll.kernel32.VirtualFreeEx
OpenProcess = ctypes.windll.kernel32.OpenProcess
WriteProcessMemory = ctypes.windll.kernel32.WriteProcessMemory
ReadProcessMemory = ctypes.windll.kernel32.ReadProcessMemory
memcpy = ctypes.cdll.msvcrt.memcpy
def readListViewItems(hwnd, column_index=0):
# Allocate virtual memory inside target process
pid = ctypes.create_string_buffer(4)
p_pid = ctypes.addressof(pid)
GetWindowThreadProcessId(hwnd, p_pid) # process owning the given hwnd
hProcHnd = OpenProcess(PROCESS_ALL_ACCESS, False, struct.unpack("i",pid)[0])
pLVI = VirtualAllocEx(hProcHnd, 0, 4096, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE)
pBuffer = VirtualAllocEx(hProcHnd, 0, 4096, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE)
# Prepare an LVITEM record and write it to target process memory
lvitem_str = struct.pack('iiiiiiiii', *[0,0,column_index,0,0,pBuffer,4096,0,0])
lvitem_buffer = ctypes.create_string_buffer(lvitem_str)
copied = ctypes.create_string_buffer(4)
p_copied = ctypes.addressof(copied)
WriteProcessMemory(hProcHnd, pLVI, ctypes.addressof(lvitem_buffer), ctypes.sizeof(lvitem_buffer), p_copied)
# iterate items in the SysListView32 control
num_items = win32gui.SendMessage(hwnd, LVM_GETITEMCOUNT)
item_texts = []
for item_index in range(num_items):
win32gui.SendMessage(hwnd, LVM_GETITEMTEXT, item_index, pLVI)
target_buff = ctypes.create_string_buffer(4096)
ReadProcessMemory(hProcHnd, pBuffer, ctypes.addressof(target_buff), 4096, p_copied)
item_texts.append(target_buff.value)
VirtualFreeEx(hProcHnd, pBuffer, 0, MEM_RELEASE)
VirtualFreeEx(hProcHnd, pLVI, 0, MEM_RELEASE)
win32api.CloseHandle(hProcHnd)
return item_texts
def getSelectedListViewItem(hwnd):
return win32gui.SendMessage(hwnd, LVM_GETNEXTITEM, -1, LVNI_SELECTED)
def getSelectedListViewItems(hwnd):
items = []
item = -1
while True:
item = win32gui.SendMessage(hwnd, LVM_GETNEXTITEM, item, LVNI_SELECTED)
if item == -1:
break
items.append(item)
return items
def getEditText(hwnd):
# api returns 16 bit characters so buffer needs 1 more char for null and twice the num of chars
buf_size = (win32gui.SendMessage(hwnd, WM_GETTEXTLENGTH, 0, 0) +1 ) * 2
target_buff = ctypes.create_string_buffer(buf_size)
win32gui.SendMessage(hwnd, WM_GETTEXT, buf_size, ctypes.addressof(target_buff))
return target_buff.raw.decode('utf16')[:-1]# remove the null char on the end
def _normaliseText(controlText):
'''Remove '&' characters, and lower case.
Useful for matching control text.'''
return controlText.lower().replace('&', '')
def _windowEnumerationHandler(hwnd, resultList):
'''Pass to win32gui.EnumWindows() to generate list of window handle,
window text, window class tuples.'''
resultList.append((hwnd, win32gui.GetWindowText(hwnd), win32gui.GetClassName(hwnd)))
def searchChildWindows(currentHwnd,
wantedText=None,
wantedClass=None,
selectionFunction=None):
results = []
childWindows = []
try:
win32gui.EnumChildWindows(currentHwnd,
_windowEnumerationHandler,
childWindows)
except win32gui.error:
# This seems to mean that the control *cannot* have child windows,
# i.e. not a container.
return
for childHwnd, windowText, windowClass in childWindows:
descendentMatchingHwnds = searchChildWindows(childHwnd)
if descendentMatchingHwnds:
results += descendentMatchingHwnds
if wantedText and \
not _normaliseText(wantedText) in _normaliseText(windowText):
continue
if wantedClass and \
not windowClass == wantedClass:
continue
if selectionFunction and \
not selectionFunction(childHwnd):
continue
results.append(childHwnd)
return results
w=win32gui
while True:
time.sleep(5)
window = w.GetForegroundWindow()
print("window: %s" % window)
if (window != 0):
if (w.GetClassName(window) == 'CabinetWClass'): # the main explorer window
print("class: %s" % w.GetClassName(window))
print("text: %s " %w.GetWindowText(window))
children = list(set(searchChildWindows(window)))
addr_edit = None
file_view = None
for child in children:
if (w.GetClassName(child) == 'ComboBoxEx32'): # the address bar
addr_children = list(set(searchChildWindows(child)))
for addr_child in addr_children:
if (w.GetClassName(addr_child) == 'Edit'):
addr_edit = addr_child
pass
elif (w.GetClassName(child) == 'SysListView32'): # the list control within the window that shows the files
file_view = child
if addr_edit:
path = getEditText(addr_edit)
else:
print('something went wrong - no address bar found')
path = ''
if file_view:
files = [item.decode('utf8') for item in readListViewItems(file_view)]
indexes = getSelectedListViewItems(file_view)
print('path: %s' % path)
print('files: %s' % files)
print('selected files:')
for index in indexes:
print("\t%s - %s" % (files[index], os.path.join(path, files[index])))
else:
print('something went wrong - no file view found')
so what this does is keep checking if the active window is of the class the explorer window uses, then iterates through the children widgets to find the address bar and the file list view. Then it extracts the list of files from the listview and requests the selected indexes. it also gets and decodes the text from the address bar.
at the bottom the info is then combined to give you the complete path, the folder path, the file name or any combination thereof.
I have tested this on windows xp with python3.4, but you will need to install the win32gui and win32 conn packages.
# Import Statement.
import subprocess
# Trigger subprocess.
subprocess.popen(r'explorer /select,"C:\path\of\folder\file"'