有人可以看看并帮助我解决我的两个问题吗?
- 这是退出应用程序的正确方法吗?(见代码末尾)
# Add assemblies
Add-Type -AssemblyName System.Windows.Forms,System.Drawing
# Create a WinForms application context
$appContext = New-Object System.Windows.Forms.ApplicationContext
$programs_for_high_performance = @('reaper')
# cmd> powercfg list
$high_performance_cfg = '3XS Audio Power'
$high_performance_cfg_guid = '7ce765f7-a0a7-4b3a-89bc-8c987a923e74'
$normal_performance_cfg = 'Balanced'
$normal_performance_cfg_guid = '381b4222-f694-41f0-9685-ff5bb260df2e'
# How often to check (seconds)
$loop_delay = 10
$TimeStart = [int](Get-Date -UFormat %s -Millisecond 0)
# Set Tray Icon
$icon = [System.Drawing.Icon]::ExtractAssociatedIcon("C:\Windows\System32\resmon.exe")
# Create a notify icon
$script:TrayIcon = New-Object System.Windows.Forms.NotifyIcon
$TrayIcon.Icon = $icon
$current = powercfg -getactivescheme
$current -match '\((.+)\)'
$scheme = $Matches[1]
$TrayIcon.Text = $scheme
$Menu_Exit = New-Object System.Windows.Forms.MenuItem
$Menu_Exit.Text = "Exit"
# Systray menu
$TrayIcon.ContextMenu = New-Object System.Windows.Forms.ContextMenu
$TrayIcon.ContextMenu.MenuItems.AddRange($Menu_Exit)
# 1 IS THIS THE CORRECT WAY? -----
$Menu_Exit.add_Click({
$TrayIcon.Dispose()
$appContext.ExitThread()
$appContext.Dispose()
[System.GC]::Collect()
Stop-Process $pid
})
$TrayIcon.Visible = $true
# Make PowerShell Disappear
$windowcode = '[DllImport("user32.dll")] public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);'
$asyncwindow = Add-Type -MemberDefinition $windowcode -name Win32ShowWindowAsync -namespace Win32Functions -PassThru
$null = $asyncwindow::ShowWindowAsync((Get-Process -PID $pid).MainWindowHandle, 0)
[void][System.Windows.Forms.Application]::Run($appContext)
- 如何将以下循环添加到正在运行的 ApplicationContext 循环中?
# Check and change powerplan
While ($appContext) # Basically, I should be looking if the Application is running?
{
$TimeNow = [int](Get-Date -UFormat %s -Millisecond 0)
If ($TimeNow - $TimeStart -ge $loop_delay) {
$TimeStart = $TimeNow
$programs_for_high_performance_running = $False
for ($i = 0 ; $i -le $programs_for_high_performance.Length – 1 ; $i++)
{
Get-Process -ErrorAction SilentlyContinue -Name $programs_for_high_performance[$i]
$running = $?
if ($running -eq $True)
{
$programs_for_high_performance_running = $True
# break
}
}
$current = powercfg -getactivescheme
if ($programs_for_high_performance_running -eq $True)
{
# Special programs running
if ($current -match $high_performance_cfg_guid -eq $False)
{
# Switch to High performance
powercfg -setactive $high_performance_cfg_guid
$TrayIcon.Text = $high_performance_cfg
}
}
else
{
# No special programs running
if ($current -match $normal_performance_cfg_guid -eq $False)
{
# Switch to Balanced performance
powercfg -setactive $normal_performance_cfg_guid
$TrayIcon.Text = $normal_performance_cfg
}
}
}
}
谢谢!
PS。我正在尝试将我发现的两个脚本合并为一个(1、2)。该脚本检查进程是否正在运行(收割机),如果是,则将电源计划方案设置为高性能,如果不是,则设置为平衡。托盘图标显示当前的电源计划方案。