Windows 10如何编程实现开机时在第二虚拟桌面启动指定程序
实现Windows 10程序在第二虚拟桌面开机启动的方案
核心原理
Win10及以上系统内置了IVirtualDesktopManager COM接口,支持查询虚拟桌面ID、移动指定窗口到目标虚拟桌面。你可以选择写一个辅助启动器(放在启动文件夹替代原来的程序快捷方式),或者直接在目标程序源码里集成自动转移桌面的逻辑即可实现需求。
方案1:免编译PowerShell启动脚本(推荐,部署快)
前置准备
- 手动按
ctrl + win + 右方向键切换到你要放程序的第二虚拟桌面 - 运行PowerShell执行以下代码,获取第二桌面的GUID,保存备用:
Add-Type @" using System; using System.Runtime.InteropServices; [Guid("a5cd92ff-29be-453c-b449-8f078469916a")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface IVirtualDesktopManager { int IsWindowOnCurrentVirtualDesktop(IntPtr hWnd, out bool onCurrentDesktop); int GetWindowDesktopId(IntPtr hWnd, out Guid desktopId); int MoveWindowToDesktop(IntPtr hWnd, ref Guid desktopId); int GetCurrentDesktopId(out Guid desktopId); } "@ $manager = [Activator]::CreateInstance([Type]::GetTypeFromCLSID([Guid]"aa509086-5ca9-4c25-8f95-589d3c07b48a")) -as "IVirtualDesktopManager" $manager.GetCurrentDesktopId([ref]$id) Write-Host "第二桌面GUID:$id"
编写启动脚本
把以下内容保存为StartupToSecondDesktop.ps1,替换里面的对应参数:
Add-Type @" using System; using System.Runtime.InteropServices; [Guid("a5cd92ff-29be-453c-b449-8f078469916a")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface IVirtualDesktopManager { int IsWindowOnCurrentVirtualDesktop(IntPtr hWnd, out bool onCurrentDesktop); int GetWindowDesktopId(IntPtr hWnd, out Guid desktopId); int MoveWindowToDesktop(IntPtr hWnd, ref Guid desktopId); int GetCurrentDesktopId(out Guid desktopId); } public class Win32API { [DllImport("user32.dll", SetLastError = true)] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); } "@ # -------------------------- 替换以下参数 -------------------------- $targetAppPath = "C:\你的程序路径\程序名.exe" # 替换为你的目标程序完整路径 $appWindowTitle = "你的程序窗口标题" # 替换为你的程序启动后的主窗口标题 $secondDesktopGuid = [Guid]"刚才获取到的第二桌面GUID" # 替换为你之前拿到的第二桌面GUID $waitAppLoadTime = 3 # 根据你的程序启动速度调整等待时间,单位秒 # ------------------------------------------------------------------ # 启动目标程序 Start-Process -FilePath $targetAppPath # 等待程序主窗口加载完成 Start-Sleep -Seconds $waitAppLoadTime # 获取程序主窗口句柄 $hWnd = [Win32API]::FindWindow($null, $appWindowTitle) if ($hWnd -eq [IntPtr]::Zero) { Write-Error "未找到目标程序窗口,可尝试调大等待时间" exit 1 } # 移动窗口到第二虚拟桌面 $desktopManager = [Activator]::CreateInstance([Type]::GetTypeFromCLSID([Guid]"aa509086-5ca9-4c25-8f95-589d3c07b48a")) -as "IVirtualDesktopManager" $desktopManager.MoveWindowToDesktop($hWnd, [ref]$secondDesktopGuid)
部署到开机启动
- 给上面的.ps1脚本创建快捷方式
- 右键快捷方式打开属性,把「目标」栏的内容改为:
powershell.exe -ExecutionPolicy Bypass -File "你保存的脚本完整路径" - 把这个快捷方式放到Windows启动文件夹(路径:
shell:startup,按Win+R输入回车就能打开),替换原来的程序快捷方式即可。
方案2:在目标程序源码中集成(最稳定)
如果你有权限修改目标程序的源码,直接在程序主窗口初始化完成的逻辑后,调用上面提到的IVirtualDesktopManager的MoveWindowToDesktop方法,把自身窗口移到提前配置好的第二桌面GUID即可,不需要额外的启动脚本。
注意事项
- 该方案兼容Win10 1903及以上所有版本,不会隐藏程序,用户切换到第二桌面就能正常看到和操作程序
- 如果你的程序启动时会弹出多个窗口,只需要找到主窗口句柄移动即可,子窗口会自动跟随主桌面归属
内容的提问来源于stack exchange,提问作者SHC MostWanted
相关产品推荐
相关产品推荐

