SendKeys and Python 2.7

Jakson A. Aquino jaksonaquino at gmail.com
Sat Sep 11 02:45:04 CEST 2010


On Thu, Sep 9, 2010 at 8:24 PM, Jakson A. Aquino <jaksonaquino at gmail.com> wrote:
> On Thu, Sep 9, 2010 at 5:40 PM, Michel Claveau - MVP
> <enleverLesX_XXmcX at xmclavxeaux.com.invalid> wrote:
>> Hi!
>>
>> Example for send ^V  (with PyWin32):
>>
>>  import time,win32api,win32con
>>  win32api.keybd_event(win32con.VK_CONTROL, 0, 0, 0)
>>  win32api.keybd_event(ord('V'), 0, win32con.KEYEVENTF_EXTENDEDKEY | 0, 0)
>>  time.sleep(0.05)
>>  win32api.keybd_event(ord('V'), 0, win32con.KEYEVENTF_EXTENDEDKEY | win32con.KEYEVENTF_KEYUP, 0)
>>  win32api.keybd_event(win32con.VK_CONTROL, 0, win32con.KEYEVENTF_KEYUP, 0)
>
> Thank you very much! Your code solved my problem. I added some lines
> to set the focus into R before the ^V and then back to Vim:

Unfortunately, I was wrong. Your code do send the ^v as expected, but
I have problem with the selection of the Windows which will receive
the ^v. The code above was OK in a Windows XP running inside
VirtualBox, but when tested in a real machine, it proved to be highly
inconsistent. Sometimes the ^v gets pasted into R, but more frequently
it is pasted into Vim itself or nowhere. Below is the complete code
that I'm using. It's a vim script. The python code is delimited by
"python << EOL" and "EOL":

function! SendToRPy(aString)
python << EOL
import time
import win32api
import win32con
import win32com.client
import win32clipboard
import vim

aString = vim.eval("a:aString")
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText(aString)
win32clipboard.CloseClipboard()
shell = win32com.client.Dispatch("WScript.Shell")
ok = shell.AppActivate("R Console")
if ok:
    win32api.keybd_event(win32con.VK_CONTROL, 0, 0, 0)
    win32api.keybd_event(ord('V'), 0, win32con.KEYEVENTF_EXTENDEDKEY | 0, 0)
    time.sleep(0.05)
    win32api.keybd_event(ord('V'), 0, win32con.KEYEVENTF_EXTENDEDKEY |
win32con.KEYEVENTF_KEYUP, 0)
    win32api.keybd_event(win32con.VK_CONTROL, 0, win32con.KEYEVENTF_KEYUP, 0)
    shell.AppActivate("Vim")
else:
    vim.command("call RWarningMsg('Is R running?')")
    time.sleep(1)
EOL
endfunction

When R isn't running, the script correctly shows the warning message
"Is R running?". Does anyone know what should I do to correctly use
the AppActivate function or is there a better approach to this
problem?

Thanks!

Jakson Aquino



More information about the Python-list mailing list