windowsnwjs

Why does win.setPosition('center') move the window to top-left?


I have this code which I execute after toggling fullscreen back from fullscreen to windowed mode:

win.setPosition('center');

The window consistently appears in top-left part of the screen -- not the middle.

The manual claims at http://docs.nwjs.io/en/latest/References/Window/#winsetpositionposition :

position {String} the position of the window. There are three valid positions: null or center or mouse Move window to specified position. Currently only center is supported on all platforms, which will put window in the middle of the screen.

I tried "center" both quoted and unquoted, and even "centre" in case it was a typo in the manual.

For the record, the "mouse" value (which I don't want/need) also doesn't work; it seems to put the window in a random or semi-random place, far away from the cursor.

Windows 10. nwjs-v0.61.0-win-x64.


Solution

  • Make sure you are creating the win variable like below:

    <script>
    const win = nw.Window.get();
    
    // Move window to top left of screen
    win.moveTo(0, 0);
    
    // Move window to middle of screen
    win.setPosition('center');
    
    // Manually move window to middle of screen
    const screen = nw.Screens.screen[0].bounds;
    const x = Math.floor((screen.width - win.width) / 2);
    const y = Math.floor((screen.height - win.height) / 2);
    win.moveTo(x, y);
    </script>
    

    You can use nw.Screen.screens to see dimensions of all the monitors if you wanted to move it to a different location.