Calculator automation via sendkeys

This example opens the Windows calculator (calc) and makes some input like using the keyboard.

import win32com.client
import win32api

shell = win32com.client.Dispatch("WScript.Shell")
shell.Run("calc")
win32api.Sleep(100)
shell.AppActivate("Calculator")
win32api.Sleep(100)
shell.SendKeys("1{+}")
win32api.Sleep(500)
shell.SendKeys("2")
win32api.Sleep(500)
shell.SendKeys("~") # ~ is the same as {ENTER}
win32api.Sleep(500)
shell.SendKeys("*3")
win32api.Sleep(500)
shell.SendKeys("~")
win32api.Sleep(2500)

Controlling applications via sendkeys

With sendkeys (Python/Pywin32 uses WScript from Windows Scripting Host) one can control applications via shortcuts. eg.

This example first opens Microsoft Outlook, takes the first element, marks the full text and takes it into the clipboard (CTRL + C).

import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shell.Run("outlook")
shell.AppActivate("Outlook")
shell.SendKeys("^o", 0) # 1 für Pause = true 0 für nein
shell.SendKeys("^a", 0)
shell.SendKeys("^c", 0)

Here is a list of WScript-commands:

Key Argument
BACKSPACE {BACKSPACE}, {BS}, or {BKSP}
BREAK {BREAK}
CAPS LOCK {CAPSLOCK}
DEL or DELETE {DELETE} or {DEL}
DOWN ARROW {DOWN}
END {END}
ENTER {ENTER} or ~
ESC {ESC}
HELP {HELP}
HOME {HOME}
INS or INSERT {INSERT} or {INS}
LEFT ARROW {LEFT}
NUM LOCK {NUMLOCK}
PAGE DOWN {PGDN}
PAGE UP {PGUP}
PRINT SCREEN {PRTSC}
RIGHT ARROW {RIGHT}
SCROLL LOCK {SCROLLLOCK}
TAB {TAB}
UP ARROW {UP}
F1 {F1}
F2 {F2}
F3 {F3}
F4 {F4}
F5 {F5}
F6 {F6}
F7 {F7}
F8 {F8}
F9 {F9}
F10 {F10}
F11 {F11}
F12 {F12}
F13 {F13}
F14 {F14}
F15 {F15}
F16 {F16}

Steuerung, Shift, ALT und Enter werden wie folgt gesendet:

 

Key Special Character
SHIFT +
CTRL ^
ALT %
ENTER ~

The documentation of Sendkeys you can find at Microsoft.

Show usable ProgIDs for win32com

This example shows you the available ProgIDs of the Windows applications which are installed and ahould be usable  with win32com. My problem is, that most of the ProgIDs are shown, but not all ?!

import win32com.client
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
colItems = objSWbemServices.ExecQuery("Select * from Win32_ProgIDSpecification")
for objItem in colItems:
    print "Caption: ", objItem.Caption
    print "Check ID: ", objItem.CheckID
    print "Check Mode: ", objItem.CheckMode
    print "Description: ", objItem.Description
    print "Name: ", objItem.Name
    print "Parent: ", objItem.Parent
    print "ProgID: ", objItem.ProgID
    print "Software Element ID: ", objItem.SoftwareElementID
    print "Software Element State: ", objItem.SoftwareElementState
    print "Target Operating System: ", objItem.TargetOperatingSystem
    print "Version: ", objItem.Version
    print "-------------------------------------------------------------------\n"

Shellwindows

This example prints the name and and pathes of the open windows (Tip: You can get the CLSID with makepy in Pythonwin):

import win32com.client
# look in the makepy output for IE for the 'CLSIDToClassMap'
# dictionary, and find the entry for 'ShellWindows'
clsid='{9BA05972-F6A8-11CF-A442-00A0C90A8F39}'
ShellWindows=win32com.client.Dispatch(clsid)
for i in range(ShellWindows.Count):
    print i
    # this is the titlebar value
    print ShellWindows[i].LocationName
    # this is the current URL
    print ShellWindows[i].LocationURL
print

Print all events from Windows Event Log

This example prints all events from event log:

import win32com.client
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
colItems = objSWbemServices.ExecQuery("Select * from Win32_NTLogEvent")
for objItem in colItems:
    print "Category: ", objItem.Category
    print "Category String: ", objItem.CategoryString
    print "Computer Name: ", objItem.ComputerName
    z = objItem.Data
    if z is None:
        a = 1
    else:
        for x in z:
            print "Data: ", x
    print "Event Code: ", objItem.EventCode
    print "Event Identifier: ", objItem.EventIdentifier
    print "Event Type: ", objItem.EventType
    z = objItem.InsertionStrings
    if z is None:
        a = 1
    else:
        for x in z:
            print "Insertion Strings: ", x
    print "Logfile: ", objItem.Logfile
    print "Message: ", objItem.Message
    print "Record Number: ", objItem.RecordNumber
    print "Source Name: ", objItem.SourceName
    print "Time Generated: ", objItem.TimeGenerated
    print "Time Written: ", objItem.TimeWritten
    print "Type: ", objItem.Type
    print "User: ", objItem.User 

Shellexecute – Printing with the default application

This script prints the file in the first argument with the windows default application.

Example:

If you save the code in the file print.py:

print.py test.doc -> Opens Microsoft Word (if it is installed) and prints the file test.py to the default printer.

print.py mytextfile.txt -> Same. But prints with Notepad

from win32api import ShellExecute
from sys import argv

ShellExecute(0, "print", argv[1], None, "", 1)

Directory Watcher

You can use this script, if you want to watch for activity on a
directory. It shows you every write and delete of a file in a specified
directory.

import os, time
path_to_watch = "c:\temp"
before = dict ([(f, None) for f in os.listdir (path_to_watch)]) 
while 1: 
  time.sleep (10) 
  after = dict ([(f, None) for f in os.listdir (path_to_watch)]) 
  added = [f for f in after if not f in before] 
  removed = [f for f in before if not f in after] 
  if added: print "Added: ", ", .join (added) 
  if removed: print "Removed: ", ", ".join (removed) 
  before = after

Show all processes with IDs

This script shows all running processes with their process IDs. It uses the wmi-class from Tim Golden. Please put it into the directory where you run this script from.

import wmi 
c = wmi.WMI () 
for process in c.Win32_Process ():
    print process.ProcessId, process.Name 

Two instances of Windows Explorer (other example)

Another example which creates two Microsoft Internet Explorer instances.

import win32process, win32com.client, time 
from win32com.client import gencache
ie_tlb = gencache.EnsureModule("{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}", 0, 1, 1)

def createNewIEProcess():
  """Create new IE process and return WebBrowser2 IDisp to it.
     a work-around for win32com.client.Dispatch("InternetExplorer.App.."),
     which will NOT create a new process
     @return new WebBrowser2 instance
  """
  si = win32process.STARTUPINFO()
  dmy, dmy, newIEprocId, dmy = win32process.CreateProcess(r"C:\Program Files\Internet Explorer\iexplore.exe", None, None, None, 0, 0, None, None, si )
  time.sleep(1.0)
  for idx in range(10):
    for shellWnd in ie_tlb.ShellWindows():
      dmy, processId = win32process.GetWindowThreadProcessId(shellWnd.HWND)
      if processId == newIEprocId:
        return shellWnd

ie1 = createNewIEProcess()
ie1.Top, ie1.Left, ie1.Height, ie1.Width = 0, 0, 50, 50

Printwatcher

This script watches for activity at the installed printers and writes a logfile. It shows how much a user has printed on wich printer (works also with network printers).

But it has a proplem with counting the right amount of printed pages 🙁

It uses the wmi-class from Tim Golden, which you can download from his webpages. Please put the wmi.py in the same directory where you run this script from.

import wmi
c = wmi.WMI ()

print_job_watcher = c.watch_for (
  notification_type="Creation",
  wmi_class="Win32_PrintJob",
  delay_secs=1
)
while 1:
  pj = print_job_watcher ()
  print "User %s has submitted %d pages to printer %s" % \
    (pj.Owner, pj.TotalPages, pj.Name)