powershell脚本写一个托盘图标

1、准备ico格式图标

star_bethlehem_icon
在这里插入图片描述
文件名改为star.ico

2、安装VSCode

如何下载安装VSCode
扩展:PowerShell扩展

3、创建项目

1、运行PowerShell命令

mkdir trayicon_ps1;cd trayicon_ps1;New-Item trayicon.ps1;code .

2、将star.ico放入trayicon_ps1文件夹

4、修改trayicon.ps1的编码

选择文件trayicon.ps1
点击右下角UTF-8
在这里插入图片描述
选择通过编码保存
在这里插入图片描述
选择UTF-8 with BOM
在这里插入图片描述

5、编辑trayicon.ps1

# 脚本文件编码为UTF8 with BOM才能支持中文

# 加载WinForms程序集
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName PresentationFramework

# 图标文件路径要使用完整的路径。
$iconPath = "$(Get-Location)/star.ico"
$tooltip = "这是文字"

# 右键菜单
$contextMenu = [System.Windows.Forms.ContextMenuStrip]::new()

$menuItemMsg = [System.Windows.Forms.ToolStripMenuItem]::new()
$menuItemMsg.Text = "弹出消息框"
$menuItemMsg.add_Click({
    
     [System.Windows.MessageBox]::Show('这是消息框') })
$null = $contextMenu.Items.Add($menuItemMsg)

$menuItemExit = [System.Windows.Forms.ToolStripMenuItem]::new()
$menuItemExit.Text = "退出"
$menuItemExit.add_Click({
    
     $script:done = $true }) # 单击菜单项时,将$done设置为$true。
$null = $contextMenu.Items.Add($menuItemExit)

# 构造NotifyIcon对象。
$notifyIcon = [System.Windows.Forms.NotifyIcon]::new()
$notifyIcon.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon($iconPath)
$notifyIcon.Text = $tooltip
$notifyIcon.Visible = $true
$notifyIcon.ContextMenuStrip = $contextMenu
$notifyIcon.add_Click({
    
     
    param($evtSender, $evtArgs)
    if ($evtArgs.Button -eq [System.Windows.Forms.MouseButtons]::Left){
    
    
        [System.Windows.MessageBox]::Show("单击了图标")
    }
})

# 定义一个变量,该变量表示是否应退出脚本,并从add_Click()事件处理程序设置为$true。
$done = $false

Write-Verbose -Verbose @"
Adding a PowerShell icon to notification area (system tray).
Use the icon's context menu to quit this script, 
or press Ctrl-C in the console window.
"@

# Loop
try {
    
    
    while (-not $done) {
    
    
        # 使WinForms处理其事件。
        [System.Windows.Forms.Application]::DoEvents()
        # 睡一会儿,保持用户界面的响应。
        # 理论上可以在这里执行其他任务,只要它们快速完成,以便仍然允许足够频繁的DoEvents()调用。
        Start-Sleep -MilliSeconds 100
    }
}
finally {
    
    
    # 处理通知图标,删除图标。
    $notifyIcon.Dispose()
    Write-Verbose -Verbose 'Exiting.'
}

6、最终效果

点击右上角三角图标运行脚本
在这里插入图片描述
鼠标悬浮效果
在这里插入图片描述
鼠标单击效果
在这里插入图片描述
鼠标右键效果
在这里插入图片描述
弹出消息框按钮效果
在这里插入图片描述
退出按钮就是退出,没啥效果

7、不显示powershell窗口的方式

新建start.vbs

set ws=createobject("wscript.shell")
ws.Run "powershell.exe .\trayicon.ps1" , 0, False

双击运行即可

猜你喜欢

转载自blog.csdn.net/qq_39124701/article/details/132090720
今日推荐