2

How to get Window reference (CGWindow, NSWindow or WindowRef) from CGWindowID in Swift on XCode 7.3 Mac Playground?

I referenced from Apple's document - Window Manager Reference, and from the sample code SonofGrab, but I didn't find an answer in obj-C nor Swift.

How should I do it?

allenlinli
  • 2,066
  • 3
  • 27
  • 49

1 Answers1

1

This should work for NSWindow from CGWindowID

NSWindow * ns_window;
ns_window = [NSApp windowWithWindowNumber: windowNumber];

To get CGWindowID from NSWindow use

CGWindowID window_id = (CGWindowID)[ns_window windowNumber];
Daniel Georgiev
  • 1,292
  • 16
  • 14
  • Are you sure that's how you get the `CGWindowId`? The docs for `windowNumber` say this: "note that this isn’t the same as the global window number assigned by the window server" – aleclarson Jul 29 '19 at 15:11
  • 1
    Also, note that `[NSApp windowWithWindowNumber:]` only works for windows owned by your application. – aleclarson Jul 29 '19 at 15:12
  • 2
    After some testing, `windowNumber` does appear to be correct! – aleclarson Jul 29 '19 at 15:58