8 votos

Usando applescript, ¿cómo mover una ventana a mi segunda pantalla?

He experimentado con absolutamente todas las opciones de secuencias de comandos posibles que puedo encontrar en la web, y no importa lo que haga, no puedo mover una ventana de FaceTime a mi pantalla secundaria.

Esto funciona...

tell application "System Events" to tell process "FaceTime"
  tell application "FaceTime" to activate
  tell front window to set position to {3600, 500}
end tell

pero con un defecto fatal que es que siempre se detiene en seco, en el borde derecho de la pantalla #1 (la pantalla izquierda).

Si establezco la coordenada X a algo menos de 2560 (mi ancho en ambas pantallas) entonces funciona perfectamente, pero cualquier intento de moverlo más a la derecha, y por lo tanto en la pantalla #2, no funcionará.

No sé si está relacionado, pero mi pantalla principal es una Dell externa, y mi pantalla secundaria es la pantalla integrada del iMac de 27". Dell a la izquierda, iMac a la derecha.

Sin embargo, si arrastro manualmente la ventana a la pantalla 2 y ejecuto el mismo script anterior, entonces se posiciona correctamente en la pantalla 2. Parece que los números son relativos a la pantalla en la que la ventana está actualmente. ¿Cómo puedo conseguir que la ventana se posicione absolutamente en la pantalla 2?

0 votos

Intento salvarte aquí... bettertouchtool para la gestión de ventanas... no uses applescript a menos que sea necesario.

1 votos

Gracias por la información, pero esta necesidad era de 2012 y ya no lo es.

0 votos

Luego seguiré con otra aplicación opcional; Keyboard Maestro. No estoy afiliado, ¡simplemente me encantan ambas aplicaciones!

3voto

benwiggy Puntos 8

Ahora existe (a partir de Catalina?) un comando en el menú Ventana para mover la ventana actual a otra pantalla.

Así que podrías hacerlo con scripts GUI.

enter image description here

2voto

joshfindit Puntos 91

Aunque esto no responde directamente a la cuestión de usar applescript, puede ser una respuesta válida para el problema real de mover Windows.

Puede utilizar una pequeña aplicación de terceros como Pizarra .

Con una configuración menor se puede establecer que la ventana se mueva por el título cuando se inicie Slate, cuando se pulse una tecla o cuando se cumpla una condición.

También puede configurarse para que cualquier ventana se mueva a una posición concreta cuando se pulse una tecla o se cumpla una condición.

La pizarra puede ajustarse a la solicitud porque su tamaño es extremadamente pequeño y no requiere privilegios de administración.

Una buena introducción:

http://mauriciogardini.com/post/43348489262/slate-a-mac-os-x-window-manager-for-power-users

0 votos

Una alternativa muy interesante, ¡gracias! No estaba casado con el uso de AppleScript, sólo era el único enfoque que se me ocurrió. Voy a dar esta una oportunidad la próxima vez que quiero hacer esto.

2voto

Malik hassan Puntos 16

Parece que Apple ha configurado la ventana para que sepa en qué pantalla debe estar y no se extienda fuera de los límites de esa pantalla cuando se inicie.

Un efecto secundario de esto es que la aplicación hará lo mismo con las llamadas del applescript.

Esto se puede ver si se atraviesa la ventana en ambos Displays. A continuación, salga y vuelva a iniciar la aplicación.

La ventana se abrirá sólo en una de las pantallas y no se cruzará.

Si hicieras lo mismo, por ejemplo, con Safari. La ventana que tenías a horcajadas seguiría a horcajadas.

Creo que no tienes suerte de hacerlo de forma útil.

La única forma de conseguirlo fue obtener los detalles de la ventana y la pantalla del archivo plist '~/Library/Preferences/com.apple.FaceTime' mientras la ventana estaba en la segunda pantalla.

 (* read plist file *)
    do shell script "/usr/bin/defaults read ~/Library/Preferences/com.apple.FaceTime NSWindow\\ Frame\\ FaceTimeWindowFrame"

Entonces, cuando la aplicación estaba en la primera pantalla.

Ejecutar un script que salga de la aplicación, reescriba la entrada 'NSWindow Frame FaceTimeWindowFrame' en el plist con la información de la posición y la pantalla que tenía de antes.

Activa de nuevo la aplicación, que se abrirá en la segunda pantalla. Y luego moverla con el código applescript normal.

tell application "FaceTime" to quit
(do shell script "/usr/bin/defaults write ~/Library/Preferences/com.apple.FaceTime NSWindow\\ Frame\\ FaceTimeWindowFrame" & (" '2562 853 638 585 2560 240 1920 1200'") as string) --set to somewhere on my second screen

delay 1
tell application "System Events"

    tell application "FaceTime" to activate

    delay 4
    set position of window "FaceTime" of application process "FaceTime" to {3269, 315}

    end tell

Pero como he dicho no es muy útil. :-(

0 votos

WOW... eso sí que es fuerza bruta. Gracias por el esfuerzo, pero tienes razón... no es muy útil. ¡Qué mala suerte! =(

1voto

Ptujec Puntos 21

A continuación, mi solución. Redimensiona y posiciona la ventana más frontal proporcionalmente en la segunda pantalla. Son unas pocas líneas de código porque también tiene en cuenta todas las diversas opciones de cómo puede posicionar sus monitores en las preferencias del sistema y tal

# http://superuser.com/questions/331313/how-to-automagically-move-windows-between-monitors-with-one-keystroke
# https://stackoverflow.com/questions/6565703/math-algorithm-fit-image-to-screen-retain-aspect-ratio
# https://forum.latenightsw.com/t/get-sizes-of-monitor-s-via-applescript/1351/10

---
use framework "Foundation"
use framework "AppKit"
use scripting additions

set allFrames to (current application's NSScreen's screens()'s valueForKey:"frame") as list
try
    set _mon1 to item 2 of item 1 of allFrames
    set _mon2 to item 2 of item 2 of allFrames

    set _mon1Width to item 1 of _mon1
    set _mon1Hight to item 2 of _mon1
    set _mon1Size to _mon1Width + _mon1Hight

    set _mon2Width to item 1 of _mon2
    set _mon2Hight to item 2 of _mon2
    set _mon2Size to _mon2Width + _mon2Hight

    set _screenWar to (_mon2Width / _mon1Width) # width adaption ratio of screen 1 & 2
    set _screenHar to (_mon2Hight / _mon1Hight) #  hight adaption ratio of screen 1 & 2 

    tell current application to set _hightoffset to do shell script "/usr/libexec/PlistBuddy -c 'Print :DisplayAnyUserSets:Configs:0:0:CurrentInfo:OriginY ' /Library/Preferences/com.apple.windowserver.displays.plist"
    set _hightoffset to _hightoffset as feet as number

    tell current application to set _widthoffset to do shell script "/usr/libexec/PlistBuddy -c 'Print :DisplayAnyUserSets:Configs:0:0:CurrentInfo:OriginX ' /Library/Preferences/com.apple.windowserver.displays.plist"
    set _widthoffset to _widthoffset as feet as number

    # detect position of the second screen in relation to the main screen
    if _mon1Width = _widthoffset then
        # say "Rechts"
        set _right to true
    else if _mon1Hight = _hightoffset then
        set _right to false
        set _bottom to true
    else if _mon2Width = -_widthoffset then
        set _right to false
        set _bottom to false
        set _left to true
    else if _mon2Hight = -_hightoffset then
        set _right to false
        set _bottom to false
        set _left to false
        set _top to true
    end if
end try

try
    tell application "System Events"
        tell (first process whose frontmost is true)
            set _windowPos to position of window 1
            set x to item 1 of _windowPos # x = position width 
            set y to item 2 of _windowPos # y = position hight 

            set _windowSize to size of window 1
            set _windowWidth to (item 1 of _windowSize)
            set _windowHight to (item 2 of _windowSize)

            # set current location (which monitor) of the frontmost window and new window size and postion 
            if _right is true then
                if x < _mon1Width then
                    set _newSize to {_windowWidth * _screenWar, _windowHight * _screenHar}
                    set _newPosition to {(x * _screenWar) + _widthoffset, ((y - 25) * _screenHar) + (_hightoffset + 25)} # menubar = 25 pixel
                    set _winLocation to "mon1"
                else
                    set _newPosition to {(x - _widthoffset) / _screenWar, ((y - (_hightoffset + 25)) / _screenHar) + 25}
                    set _newSize to {_windowWidth / _screenWar, _windowHight / _screenHar}
                    set _winLocation to "mon2"
                end if

            else if _bottom is true then
                if y < _mon1Hight then
                    set _newPosition to {(x * _screenWar) + _widthoffset, ((y - 25) * _screenHar) + (_hightoffset + 25)}
                    set _newSize to {_windowWidth * _screenWar, _windowHight * _screenHar}
                    set _winLocation to "mon1"
                else
                    set _newPosition to {(x - _widthoffset) / _screenWar, ((y - (_hightoffset + 25)) / _screenHar) + 25}
                    set _newSize to {_windowWidth / _screenWar, _windowHight / _screenHar}
                    set _winLocation to "mon2"
                end if
            else if _left is true then
                if x > -1 then
                    set _newSize to {_windowWidth * _screenWar, _windowHight * _screenHar}
                    set _newPosition to {(x * _screenWar) + _widthoffset, ((y - 25) * _screenHar) + (_hightoffset + 25)}
                    set _winLocation to "mon1"
                else
                    set _newPosition to {(x - _widthoffset) / _screenWar, ((y - (_hightoffset + 25)) / _screenHar) + 25}
                    set _newSize to {_windowWidth / _screenWar, _windowHight / _screenHar}
                    set _winLocation to "mon2"
                end if
            else if _top is true then
                if y < 25 then
                    set _newPosition to {(x - _widthoffset) / _screenWar, (y + (-_hightoffset - 25)) / _screenHar + 25}
                    set _newSize to {_windowWidth / _screenWar, (_windowHight + 25) / _screenHar - 25}
                    set _winLocation to "mon2"
                else
                    set _newSize to {_windowWidth * _screenWar, (_windowHight + 25) * _screenHar - 25}
                    set _newPosition to {(x * _screenWar) + _widthoffset, ((y - 25) * _screenHar) + _hightoffset + 25}
                    set _winLocation to "mon1"
                end if
            end if

            # checking for window loaction and whether the monitor it is located on is bigger or smaller than the other one 
            if _winLocation is "mon1" then
                if _mon1Size > _mon2Size then
                    set size of window 1 to _newSize
                    set position of window 1 to _newPosition
                else
                    set position of window 1 to _newPosition
                    set size of window 1 to _newSize
                end if

            else
                if _mon2Size > _mon1Size then
                    set size of window 1 to _newSize
                    set position of window 1 to _newPosition
                else
                    set position of window 1 to _newPosition
                    set size of window 1 to _newSize
                end if
            end if

        end tell
    end tell
end try

1voto

Heechul Ryu Puntos 1

Mi solución es utilizar tanto AppleScipt a través de Atajos y amatista

y aquí está el script

# key codes:
# 13 w
# 14 e
on run {input, parameters}
    tell application "System Events" to key code 13 using {control down, option down, shift down}
    return input
end run
# corresponds to `Throw focused window to screen 1`

AppleAyuda.com

AppleAyuda es una comunidad de usuarios de los productos de Apple en la que puedes resolver tus problemas y dudas.
Puedes consultar las preguntas de otros usuarios, hacer tus propias preguntas o resolver las de los demás.

Powered by:

X