How do I right click on a windows tray icon and clicking on item on context menu in Python?
Question: I need to right click on a Windows Notification Tray icon, and select (left
clicking) one of the items on the resulting context menu.

I have tried to use [pywinauto](http://pywinauto.googlecode.com/), and while
running this code from the code on the [How
To's](http://pywinauto.googlecode.com/hg/pywinauto/docs/HowTo.html#how-to-
access-the-system-tray-aka-systray-aka-notification-area) page: from
pywinauto.application import Application from pywinauto import taskbar

    
    
    # connect to outlook
    outlook = Application().connect_(process=4436)
    
    # click on Outlook's icon
    taskbar.ClickSystemTrayIcon(12)
    
    # Select an item in the popup menu
    outlook.PopupMenu.MenuClick("Cancel Server Request")
    

I am getting the following error:

    
    
    Traceback (most recent call last):
      File "C:\dev\consumertms\temp.py", line 25, in <module>
        taskbar.ClickSystemTrayIcon(12)
      File "C:\Python27\lib\site-packages\pywinauto\taskbar.py", line 52, in ClickSystemTrayIcon
        button = _get_visible_button_index(button)
      File "C:\Python27\lib\site-packages\pywinauto\taskbar.py", line 42, in _get_visible_button_index
        if not SystemTrayIcons.GetButton(i).fsState & \
      File "C:\Python27\lib\site-packages\pywinauto\controls\common_controls.py", line 1878, in GetButton
        button.idCommand)
    RuntimeError: GetButtonInfo failed for button with command id 2
    

I am currently running Windows 8, but will require this to run on Windows XP
onwards.

I have searched around and was unable to find a workaround for this.

My Question: Is there a workaround for this error? If not, is there some other
Python module I can use to automate this process? Some code snippets will be
very much appreciated.

Thanks


Answer: A context menu or dropdown menu can be a window context on it's own. You will
need to find it with _findwindows.find_windows()_.

I encountered this problem when I needed to access dropdown menu items on a
non-native GUI. The easiest way to get the class name of that windows is by
using SWAPY, which lists all window objects and creates handy pywinauto code
<https://code.google.com/p/swapy/>.

A typical approach would be like this:

    
    
    outlook = Application().connect_(process=4436)
    taskbar.ClickSystemTrayIcon(12)
    
    # Use SWAPY to find the class name of the popup menu
    w_handle = findwindows.find_windows(title=u'', class_name='name-found-in-SWAPY')[0]
    popup = app.window_(handle=w_handle)
    popup.Click(coords=(x,y))
    

