如何告诉 python 在桌面 2 和 3 中启动应用程序?
这可以通过启动您的应用程序来实现subprocess.Popen()
,然后通过调用更改虚拟桌面GoToDesktopNumber()
from VirtualDesktopAccessor.dll
在...的帮助下ctypes
,然后再次启动您的应用程序。使用 64 位 Windows 10 版本 10.0.18363.720 进行测试。
VirtualDesktopAccessor.dll by 贾里·佩纳宁将函数导出为大多数未记录的(Microsoft)虚拟桌面 API 的一部分。放在dll在当前工作目录中。
import ctypes, time, shlex, subprocess
def launch_apps_to_virtual_desktops(command_lines, desktops=3):
virtual_desktop_accessor = ctypes.WinDLL("VirtualDesktopAccessor.dll")
for i in range(desktops):
virtual_desktop_accessor.GoToDesktopNumber(i)
time.sleep(0.25) # Wait for the desktop to switch
for command_line in command_lines:
if command_line:
subprocess.Popen(shlex.split(command_line))
time.sleep(2) # Wait for apps to open their windows
virtual_desktop_accessor.GoToDesktopNumber(0) # Go back to the 1st desktop
command_lines = r"""
"C:\Program Files (x86)\Google\Chrome Beta\Application\chrome.exe"
"C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe" "C:\StudyGuide.pdf"
"C:\Program Files\Mozilla Firefox\firefox.exe"
"C:\Program Files\VideoLAN\VLC\vlc.exe"
""".splitlines()
launch_apps_to_virtual_desktops(command_lines)
The time.sleep()
之所以需要调用,是因为 Windows 不会立即更改虚拟桌面(可能是因为动画),并且需要给进程时间来创建窗口。您可能需要调整时间。
请注意,某些应用程序仅允许一个实例/进程,因此您无法为每个虚拟桌面获取多个单独的窗口(例如,使用默认设置的 Adobe Reader)。
我尝试的另一个策略是启动应用程序,休眠一会儿以允许创建窗口,然后调用MoveWindowToDesktopNumber()
将新进程创建的每个窗口移动到不同的虚拟桌面。问题是,对于像 Chrome 或 Firefox 这样的应用程序,如果现有进程已经存在,新进程会立即关闭,因此它不会将新窗口(实际上属于另一个较旧的进程)移动到另一个桌面。
import ctypes, time, shlex, subprocess
from ctypes.wintypes import *
from ctypes import windll, byref
def get_windows(pid):
current_window = 0
pid_local = DWORD()
while True:
current_window = windll.User32.FindWindowExA(0, current_window, 0, 0)
windll.user32.GetWindowThreadProcessId(current_window, byref(pid_local))
if pid == pid_local.value:
yield current_window
if current_window == 0:
return
def launch_apps_to_virtual_desktops_by_moving(command_lines, desktops=3):
virtual_desktop_accessor = ctypes.WinDLL("VirtualDesktopAccessor.dll")
for i in range(desktops):
pids = []
for command_line in command_lines:
if command_line:
args = shlex.split(command_line)
pids.append(subprocess.Popen(args).pid)
time.sleep(3)
for pid in pids:
for window in get_windows(pid):
window = HWND(window)
virtual_desktop_accessor.MoveWindowToDesktopNumber(window, i)
command_lines = r"""
"C:\Program Files (x86)\Google\Chrome Beta\Application\chrome.exe"
"C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe" "C:\StudyGuide.pdf"
"C:\Program Files\Mozilla Firefox\firefox.exe"
"C:\Program Files\VideoLAN\VLC\vlc.exe"
""".splitlines()
launch_apps_to_virtual_desktops_by_moving(command_lines)