如何写一个脚本自动分屏

wen 实用脚本 2

本文目录导读:

如何写一个脚本自动分屏

  1. PowerShell 脚本(Windows)
  2. 快捷键分屏脚本(AutoHotkey)
  3. Python 脚本(跨平台)
  4. 带有自动化布局的脚本
  5. 简易使用说明

我来分享几种自动分屏脚本的实现方法,覆盖不同操作系统和应用场景:

PowerShell 脚本(Windows)

# window-split.ps1
# Windows 自动分屏脚本
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class Win32 {
    [DllImport("user32.dll")]
    public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
    [DllImport("user32.dll")]
    public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
}
"@
# 获取当前活动窗口
$handle = (Get-Process | Where-Object {$_.MainWindowTitle -ne ""} | Select-Object -Last 1).MainWindowHandle
# 获取屏幕分辨率
Add-Type -AssemblyName System.Windows.Forms
$screen = [System.Windows.Forms.Screen]::PrimaryScreen.WorkingArea
$width = $screen.Width
$height = $screen.Height
# 分屏函数
function Split-Screen {
    param(
        [string]$Mode = "left",  # left, right, top, bottom, quarter
        [IntPtr]$WindowHandle
    )
    if ($WindowHandle -eq [IntPtr]::Zero) {
        Write-Host "No window found"
        return
    }
    switch ($Mode) {
        "left" {
            [Win32]::MoveWindow($WindowHandle, 0, 0, $width/2, $height, $true)
        }
        "right" {
            [Win32]::MoveWindow($WindowHandle, $width/2, 0, $width/2, $height, $true)
        }
        "top" {
            [Win32]::MoveWindow($WindowHandle, 0, 0, $width, $height/2, $true)
        }
        "bottom" {
            [Win32]::MoveWindow($WindowHandle, 0, $height/2, $width, $height/2, $true)
        }
        "quarter" {
            [Win32]::MoveWindow($WindowHandle, 0, 0, $width/2, $height/2, $true)
        }
    }
}
# 使用示例
Split-Screen -Mode "left" -WindowHandle $handle

快捷键分屏脚本(AutoHotkey)

; auto-split.ahk
; AutoHotkey 自动分屏脚本
; 全局设置
#SingleInstance force
CoordMode, Mouse, Screen
; 快捷键配置
; Win+1/2/3/4 分别对应四个角落
; Win+Left/Right/Up/Down 分屏
; 左半屏
#Left::
    WinGet, activeWin, ID, A
    WinRestore, ahk_id %activeWin%
    WinMove, ahk_id %activeWin%,, 0, 0, A_ScreenWidth/2, A_ScreenHeight
return
; 右半屏
#Right::
    WinGet, activeWin, ID, A
    WinRestore, ahk_id %activeWin%
    WinMove, ahk_id %activeWin%,, A_ScreenWidth/2, 0, A_ScreenWidth/2, A_ScreenHeight
return
; 上半屏
#Up::
    WinGet, activeWin, ID, A
    WinRestore, ahk_id %activeWin%
    WinMove, ahk_id %activeWin%,, 0, 0, A_ScreenWidth, A_ScreenHeight/2
return
; 下半屏
#Down::
    WinGet, activeWin, ID, A
    WinRestore, ahk_id %activeWin%
    WinMove, ahk_id %activeWin%,, 0, A_ScreenHeight/2, A_ScreenWidth, A_ScreenHeight/2
return
; 四分之一屏幕
^#1::
    WinGet, activeWin, ID, A
    WinRestore, ahk_id %activeWin%
    WinMove, ahk_id %activeWin%,, 0, 0, A_ScreenWidth/2, A_ScreenHeight/2
return
^#2::
    WinGet, activeWin, ID, A
    WinRestore, ahk_id %activeWin%
    WinMove, ahk_id %activeWin%,, A_ScreenWidth/2, 0, A_ScreenWidth/2, A_ScreenHeight/2
return
^#3::
    WinGet, activeWin, ID, A
    WinRestore, ahk_id %activeWin%
    WinMove, ahk_id %activeWin%,, 0, A_ScreenHeight/2, A_ScreenWidth/2, A_ScreenHeight/2
return
^#4::
    WinGet, activeWin, ID, A
    WinRestore, ahk_id %activeWin%
    WinMove, ahk_id %activeWin%,, A_ScreenWidth/2, A_ScreenHeight/2, A_ScreenWidth/2, A_ScreenHeight/2
return
; 三列布局
^#Left::
    WinGet, activeWin, ID, A
    WinMove, ahk_id %activeWin%,, 0, 0, A_ScreenWidth/3, A_ScreenHeight
return
^#Center::
    WinGet, activeWin, ID, A
    WinMove, ahk_id %activeWin%,, A_ScreenWidth/3, 0, A_ScreenWidth/3, A_ScreenHeight
return
^#Right::
    WinGet, activeWin, ID, A
    WinMove, ahk_id %activeWin%,, 2*A_ScreenWidth/3, 0, A_ScreenWidth/3, A_ScreenHeight
return

Python 脚本(跨平台)

# split_screen.py
# Python 自动分屏脚本
import tkinter as tk
import subprocess
import sys
import os
class ScreenSplitter:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("Screen Splitter")
        self.root.geometry("300x400")
        # 获取屏幕尺寸
        self.screen_width = self.root.winfo_screenwidth()
        self.screen_height = self.root.winfo_screenheight()
        self.setup_ui()
    def setup_ui(self):
        # 标题
        title = tk.Label(self.root, text="分屏工具", font=("Arial", 16, "bold"))
        title.pack(pady=10)
        # 分屏按钮
        buttons = [
            ("左半屏", self.split_left),
            ("右半屏", self.split_right),
            ("上半屏", self.split_top),
            ("下半屏", self.split_bottom),
            ("四分之一屏", self.split_quarter)
        ]
        for text, command in buttons:
            btn = tk.Button(self.root, text=text, command=command, 
                          width=20, height=2, bg="#4CAF50", fg="white")
            btn.pack(pady=5)
        # 自定义布局
        custom_frame = tk.Frame(self.root)
        custom_frame.pack(pady=20)
        tk.Label(custom_frame, text="自定义百分比:").pack()
        self.width_var = tk.DoubleVar(value=50)
        self.height_var = tk.DoubleVar(value=50)
        width_scale = tk.Scale(custom_frame, from_=10, to=90, orient=tk.HORIZONTAL,
                               label="宽度%", variable=self.width_var)
        width_scale.pack()
        height_scale = tk.Scale(custom_frame, from_=10, to=90, orient=tk.HORIZONTAL,
                                label="高度%", variable=self.height_var)
        height_scale.pack()
        apply_btn = tk.Button(custom_frame, text="应用自定义分屏", 
                             command=self.custom_split, bg="#2196F3", fg="white")
        apply_btn.pack(pady=10)
    def get_active_window_id(self):
        # Linux 使用 xdotool
        if sys.platform.startswith('linux'):
            try:
                result = subprocess.run(['xdotool', 'getactivewindow'], 
                                     capture_output=True, text=True)
                return result.stdout.strip()
            except:
                print("需要安装 xdotool: sudo apt install xdotool")
                return None
        return None
    def move_window(self, x, y, width, height):
        window_id = self.get_active_window_id()
        if window_id:
            subprocess.run(['xdotool', 'windowmove', window_id, str(x), str(y)])
            subprocess.run(['xdotool', 'windowsize', window_id, str(width), str(height)])
    def split_left(self):
        self.move_window(0, 0, self.screen_width//2, self.screen_height)
    def split_right(self):
        self.move_window(self.screen_width//2, 0, self.screen_width//2, self.screen_height)
    def split_top(self):
        self.move_window(0, 0, self.screen_width, self.screen_height//2)
    def split_bottom(self):
        self.move_window(0, self.screen_height//2, self.screen_width, self.screen_height//2)
    def split_quarter(self):
        self.move_window(0, 0, self.screen_width//2, self.screen_height//2)
    def custom_split(self):
        width_pct = self.width_var.get() / 100
        height_pct = self.height_var.get() / 100
        self.move_window(0, 0, int(self.screen_width * width_pct), 
                        int(self.screen_height * height_pct))
    def run(self):
        self.root.mainloop()
# 命令行模式
def command_line_mode():
    import argparse
    parser = argparse.ArgumentParser(description="自动分屏工具")
    parser.add_argument("--mode", choices=["left", "right", "top", "bottom", "quarter"],
                       help="分屏模式")
    parser.add_argument("--left", type=int, default=0, help="左边距")
    parser.add_argument("--top", type=int, default=0, help="上边距")
    parser.add_argument("--width", type=int, default=50, help="宽度百分比")
    parser.add_argument("--height", type=int, default=50, help="高度百分比")
    args = parser.parse_args()
    splitter = ScreenSplitter()
    if args.mode == "left":
        splitter.split_left()
    elif args.mode == "right":
        splitter.split_right()
    elif args.mode == "top":
        splitter.split_top()
    elif args.mode == "bottom":
        splitter.split_bottom()
    elif args.mode == "quarter":
        splitter.split_quarter()
    else:
        # 自定义分屏
        import tkinter as tk
        temp_root = tk.Tk()
        screen_w = temp_root.winfo_screenwidth()
        screen_h = temp_root.winfo_screenheight()
        temp_root.destroy()
        width = int(screen_w * args.width / 100)
        height = int(screen_h * args.height / 100)
        splitter.move_window(args.left, args.top, width, height)
if __name__ == "__main__":
    if len(sys.argv) > 1:
        command_line_mode()
    else:
        app = ScreenSplitter()
        app.run()

带有自动化布局的脚本

# auto_layout.py
# 自动化多窗口布局脚本
import subprocess
import time
import os
class AutoLayout:
    def __init__(self):
        self.processes = []
    def launch_applications(self, apps):
        """启动多个应用程序"""
        for app in apps:
            try:
                if os.name == 'nt':  # Windows
                    process = subprocess.Popen(app, shell=True)
                else:  # Linux/Mac
                    process = subprocess.Popen(app.split())
                self.processes.append(process)
                time.sleep(2)  # 等待窗口加载
            except Exception as e:
                print(f"启动 {app} 失败: {e}")
    def get_window_info(self, window_title):
        """获取窗口信息"""
        if os.name == 'nt':  # Windows
            import win32gui
            import win32con
            def callback(hwnd, windows):
                if win32gui.IsWindowVisible(hwnd):
                    title = win32gui.GetWindowText(hwnd)
                    if window_title.lower() in title.lower():
                        windows.append(hwnd)
                return True
            windows = []
            win32gui.EnumWindows(callback, windows)
            return windows[0] if windows else None
        else:  # Linux
            try:
                result = subprocess.run(
                    ['xdotool', 'search', '--name', window_title],
                    capture_output=True, text=True
                )
                windows = result.stdout.strip().split('\n')
                return windows[0] if windows and windows[0] else None
            except:
                return None
    def arrange_windows_grid(self, window_titles, rows, cols):
        """网格布局窗口"""
        screen_width = 1920
        screen_height = 1080
        cell_width = screen_width // cols
        cell_height = screen_height // rows
        for i, title in enumerate(window_titles):
            window_id = self.get_window_info(title)
            if window_id:
                row = i // cols
                col = i % cols
                x = col * cell_width
                y = row * cell_height
                if os.name == 'nt':  # Windows
                    import win32gui
                    win32gui.SetWindowPos(window_id, 0, x, y, 
                                        cell_width, cell_height, 0)
                else:  # Linux
                    subprocess.run(['xdotool', 'windowmove', window_id, 
                                  str(x), str(y)])
                    subprocess.run(['xdotool', 'windowsize', window_id, 
                                  str(cell_width), str(cell_height)])
                time.sleep(0.5)
# 使用示例
if __name__ == "__main__":
    layout = AutoLayout()
    # 启动应用程序
    apps = ["notepad.exe", "cmd.exe", "calc.exe", "mspaint.exe"]
    if os.name != 'nt':
        apps = ["gedit", "gnome-terminal", "gnome-calculator"]
    layout.launch_applications(apps)
    # 等待应用程序加载
    time.sleep(5)
    # 2x2网格布局s = ["Notepad", "Command", "Calculator", "Paint"]
    if os.name != 'nt':
        titles = ["gedit", "Terminal", "Calculator"]
    layout.arrange_windows_grid(titles, 2, 2)

简易使用说明

Windows 用户:

  1. 保存 PowerShell 脚本为 .ps1 文件
  2. 右键点击文件 → "使用 PowerShell 运行"
  3. 或者使用 AutoHotkey 版本,安装后双击运行

Linux 用户:

# 安装依赖
sudo apt install xdotool python3-tk
# 运行 Python 脚本
python3 split_screen.py --mode left  # 命令行模式
python3 split_screen.py              # GUI模式

自定义使用:

# 自定义分屏(50%宽度,100%高度)
python3 split_screen.py --width 50 --height 100
# 指定位置
python3 split_screen.py --left 100 --top 50 --width 40 --height 60

选择适合你需求的脚本,或者根据具体情况修改使用,需要我详细解释某个部分吗?

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