Sending keyboard and mouse events to unfocused window.

Is there any way to send key/mouse events to unfocused windows? Currently my code looks like this:

let src = CGEventSource(stateID: CGEventSourceStateID.hidSystemState)
      let key_d = CGEvent(keyboardEventSource: src, virtualKey: 0x12, keyDown: true) // key "1" press
      let key_u = CGEvent(keyboardEventSource: src, virtualKey: 0x12, keyDown: false) // key "1" release
      key_d?.postToPid( (Int32)(pid) )
      key_u?.postToPid( (Int32)(pid) )

Unfortunately this is working just for application, which owns menu bar.

I was trying different methods, but none of them is working. I would love to send those events directly to app by selecting specific window ID instead of pid, but anything working with not-focused apps will be good.

Answers

Any ideas?