golang 定期切换浏览器页面小工具

==引入包==

go get github.com/go-vgo/robotgo

 

==源代码==

package main

import (
    "fmt"
    "github.com/go-vgo/robotgo"
    "strconv"
    "strings"
    "time"
)

func main() {
    browserMap := make(map[string]string)
    browserMap["chrome.exe"] = "谷歌浏览器"
    browserMap["iexplore.exe"] = "IE浏览器"
    browserMap["sogouexplorer.exe"] = "搜狗浏览器"
    browserMap["firefox.exe"] = "火狐浏览器"
    browserMap["opera.exe"] = "Opera浏览器"
    browserMap["safari.exe"] = "Safari浏览器"
    browserMap["360se.exe"] = "360浏览器"
    browserMap["maxthon.exe"] = "遨游浏览器"
    browserMap["netscape.exe"] = "网景浏览器"

    // 浏览器集合
    fmt.Println("工具支持以下浏览器:")
    i := 1
    for id, name := range browserMap {
        fmt.Println(fmt.Sprintf("%d.%s(%s)", i, name, id))
        i++
    }
    fmt.Println()

    // 输入切换时间
    var input string
    fmt.Print("请输入切换间隔时间(秒): ")
    _, err := fmt.Scanln(&input)
    if err != nil {
        fmt.Println(err.Error())
        return
    }
    interval, err := strconv.Atoi(input)
    if err != nil {
        fmt.Println(err.Error())
        return
    }

    // 启动定时任务
    ticker := time.NewTicker(time.Second * time.Duration(interval))
    defer ticker.Stop()

    for {
        select {
        case <-ticker.C:
            switchPage(browserMap)
        }
    }
}

func switchPage(browserMap map[string]string) {
    // 获取当前窗口
    pid := robotgo.GetPid()
    name, err := robotgo.FindName(pid)

    // 是否在范围内
    lower := strings.ToLower(name)
    _, has := browserMap[lower]
    if !has {
        fmt.Println(fmt.Sprintf("当前窗口(%s)非Chrome浏览器。", lower))
        return
    }

    // 模拟按下Ctrl键
    err = robotgo.KeyToggle(robotgo.Ctrl, "down")
    if err != nil {
        fmt.Println(err.Error())
        return
    }
    time.Sleep(100 * time.Millisecond)

    // 模拟按下PageDown键
    err = robotgo.KeyTap(robotgo.Pagedown)
    if err != nil {
        fmt.Println(err.Error())
        return
    }
    time.Sleep(100 * time.Millisecond)

    // 模拟释放Ctrl键
    err = robotgo.KeyToggle(robotgo.Ctrl, "up")
    if err != nil {
        fmt.Println(err.Error())
        return
    }
    fmt.Println(fmt.Sprintf("%s %s", "切换页面成功", time.Now().Format("2006-01-02 15:04:05")))
}

 

==运行效果==

 

posted @ 2024-01-09 18:18  大墨垂杨  阅读(76)  评论(0编辑  收藏  举报