Home > Software design >  How can I programmatically display a window on a specific screen (i.e., main display as opposed to e
How can I programmatically display a window on a specific screen (i.e., main display as opposed to e

Time:12-07

I am facing difficulty presenting my app window on a specific screen (i.e., the main display as opposed to my external display). The reason why I want to display my app on the main display is that I would like to blank out my external display later on by using CGDisplayCapture(CGDirectDisplayID(2)).

I found several suggestions and implementations as follows.

Swift 3/macOS: Open window on certain screen

How to change the NSScreen a NSWindow appears on

Show window on multiple displays on os x

how to move NSWindow to a particular screen?

However, I cannot figure out how to actualize this in Swift 5. This could be because the previous posts got outdated. For example, the following my code (based on Swift 3/macOS: Open window on certain screen) does not work... it does not do anything.

override func viewDidLoad() {
    super.viewDidLoad()
    
    //set up the main display as the display where window shows up
    let screens = NSScreen.screens
    var pos = NSPoint()
    pos.x = screens[0].visibleFrame.midX
    pos.y = screens[0].visibleFrame.midY
    self.view.window?.setFrameOrigin(pos)

I would appreciate it if I could hear how to implement this.

CodePudding user response:

The ViewController isn't the right place to be doing this. Either use a WindowController and put the relevant code in windowDidLoad, or, if you really want a view that causes its parent window to fill the primary display, override viewDidMoveToWindow on your view. (The latter would be a bit odd in most cases IMO.)

CodePudding user response:

Thanks to the question posed by @Willeke, I was able to use the following code to display the window on the main screen (as opposed to external displays). I just needed to use DispatchQueue.main.async {}.

   override func viewDidLoad() {
         super.viewDidLoad()
         DispatchQueue.main.async {
             
             //set up the main display as the display where window shows up
             let screens = NSScreen.screens
             var pos = NSPoint()
             pos.x = screens[0].visibleFrame.midX
             pos.y = screens[0].visibleFrame.midY
             self.view.window?.setFrameOrigin(pos)
             
         }
    }
  • Related