如何用脚本快速切换应用

wen 实用脚本 1

本文目录导读:

如何用脚本快速切换应用

  1. Windows 系统
  2. macOS 系统
  3. 跨平台解决方案
  4. 快捷操作方案
  5. 最实用组合方案
  6. 自动化智能切换
  7. 💡 最佳实践建议

Windows 系统

AutoHotkey(最强大,推荐)

; 快速切换:Win+1 切换到浏览器,Win+2 切换到微信
#1::Run "C:\Program Files\Google\Chrome\Application\chrome.exe"
#2::Run "C:\Program Files\Tencent\WeChat\WeChat.exe"
; 或:如果已打开则激活窗口
#1::
if WinExist("ahk_exe chrome.exe")
    WinActivate
else
    Run "chrome.exe"
return

PowerShell 脚本

# 保存为 switch.ps1
param([string]$appName)
$process = Get-Process -Name $appName -ErrorAction SilentlyContinue
if ($process) {
    $process.MainWindowHandle | ForEach-Object { 
        Add-Type @"
using System;
using System.Runtime.InteropServices;
public class WinAPI {
    [DllImport("user32.dll")]
    public static extern bool SetForegroundWindow(IntPtr hWnd);
}
"@
        [WinAPI]::SetForegroundWindow($_)
    }
} else {
    Start-Process $appName
}

macOS 系统

AppleScript(系统原生)

-- 保存为 switch.scpt
on run argv
    set appName to item 1 of argv
    tell application appName to activate
end run

结合快捷键使用(如 BetterTouchTool):

# 命令行快速切换
osascript -e 'tell application "Safari" to activate'

使用 Raycast / Alfred(推荐)

# Raycast 中设置 Hotkey 触发
osascript -e 'tell application "System Events" to key code 48 using command down'

跨平台解决方案

使用 fzf 模糊搜索切换(程序员最爱)

#!/bin/bash
# 保存为 switch.sh
app=$(ls /Applications/ | fzf --header="选择应用")
open -a "$app"  # macOS
# Windows 可用:powershell -Command "Get-Process | fzf | Select -ExpandProperty Name"

使用 Python 自动化(全平台)

import subprocess
import pyautogui
def switch_app(app_name):
    if sys.platform == "darwin":  # macOS
        subprocess.run(['osascript', '-e', f'tell application "{app_name}" to activate'])
    elif sys.platform == "win32":  # Windows
        subprocess.run(['powershell', '-Command', f'Start-Process "{app_name}"'])
    else:  # Linux
        subprocess.run(['wmctrl', '-a', app_name])
# 调用示例
switch_app("Google Chrome")

快捷操作方案

Alfred Workflow(macOS)

{
    "keyword": "sw",
    "action": "open -a {query}",
    "subtitle": "快速启动应用"
}

PowerToys Run(Windows 免费)

  • Alt + Space,输入应用名直接回车即可切换

最实用组合方案

建议使用这个组合:

  1. macOS:安装 Raycast + 设置快捷键 Cmd+Space 输入应用名,或设置全局热键:

    # 让 Raycast 启动即切换
    raycast switch "Google Chrome"
  2. Windows:使用 Alt+Tab + AutoHotkey 增强:

    ; 自定义切换
    CapsLock & c::AltTab
    CapsLock & v::ShiftAltTab
  3. Linux:使用 wmctrl 脚本:

    # 长按 Win 键切换
    wmctrl -a "$(zenity --entry --text='输入应用名')"

自动化智能切换

按需切换脚本

#!/bin/bash
# 智能切换:根据当前任务自动切换窗口
if pgrep -x "code" > /dev/null; then
    wmctrl -a "Visual Studio Code"
elif pgrep -x "chrome" > /dev/null; then
    wmctrl -a "Google Chrome"
elif pgrep -x "gedit" > /dev/null; then
    wmctrl -a "Gedit"
fi

💡 最佳实践建议

  1. 优先使用系统原生功能:macOS 的 Cmd+Tab、Windows 的 Alt+Tab
  2. 设置全局快捷键:如 Cmd+1/2/3Ctrl+1/2/3
  3. 配合窗口管理器:如 Amethyst、yabai、PowerToys FancyZones
  4. 自动化工作流:使用 Hammerspoon(macOS)或 AutoHotkey(Windows)

抱歉,评论功能暂时关闭!