0

I'm trying to simulate double fn keypress on mac to start dictation so far i have read all the docs on SO and applied a few solutions, but all in vain. I'm trying to open dictation from python code. executed from terminal. So far i'have tried this but with no success.

from Quartz.CoreGraphics import CGEventCreateKeyboardEvent
from Quartz.CoreGraphics import CGEventPost
from Quartz.CoreGraphics import kCGHIDEventTap

evt = [CGEventCreateKeyboardEvent(None, 0x3f, True), 
        CGEventCreateKeyboardEvent(None, 0x3f, False), 
        CGEventCreateKeyboardEvent(None, 0x3f, True), 
        CGEventCreateKeyboardEvent(None, 0x3f, False)]
CGEventPost(kCGHIDEventTap, evt)

can anyone tell me where i'm going wrong ?

Krishna Kumar
  • 17
  • 1
  • 8
  • Do you use Apple's pre-installed version of Python? As [that seems to be necessary for Quartz.CoreGraphics to work properly](https://pythonhosted.org/pyobjc/notes/quartz-vs-coregraphics.html).. – Montmons Apr 02 '17 at 18:27
  • Also, after reading [this](http://stackoverflow.com/a/21397453/4041795) answer, I Googled for `macos CGKeyCode function keys` and I found [this](http://stackoverflow.com/q/3202629/4041795) post. Open the file referenced in the answer (`/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h`) I found the corresponding code for `kVK_Function` to be `0x3F` so not `0x3f` (like you seem to be using..?), and I found the `kFunctionKeyCharCode` to be `16`. Not sure if that helps? – Montmons Apr 02 '17 at 18:37
  • @SB87 i'm using python under virtual environment. Is there any way to access it from there ? yeah i tried that too and with 63 too. but didn't work – Krishna Kumar Apr 03 '17 at 15:30
  • Executing the system Python inside your virtualenv? Guess so.. just execute your scripts via `/usr/bin/python yourpythonscript.py`. Not sure if that is bad design though.. – Montmons Apr 03 '17 at 15:33
  • nope @SB87 this script itself is being executed in virtual environment. i'll try it out – Krishna Kumar Apr 03 '17 at 16:29

1 Answers1

0

This code working successfully:

import Quartz, AppKit

ev = AppKit.NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_(
     14,
     (0, 0),  # location
     0xa00,  
     0,
     0,
     0,
     8,
     ((0x3f - 128) << 16) | (0xa << 8),
     -1
     )
Quartz.CGEventPost(0, ev.CGEvent())

event = Quartz.CGEventCreateKeyboardEvent(None, 0x3f, True)
Quartz.CGEventSetFlags(event, 0)
Quartz.CGEventPost(Quartz.kCGHIDEventTap, event)

The problem was that you didn't specify the flags for the mouse event.The variable "ev" contains all the data where the button will be clicked.