You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell Forms:鼠标悬停时如何更改按钮的前景色与背景色

解决WinForms按钮鼠标悬停/离开时变色的问题

先纠正几个关键错误,再给出完整的可运行实现:

问题根源

  1. WinForms Button控件没有Color属性,要修改前景色用ForeColor,背景色用BackColor
  2. MouseHover事件有触发延迟(默认几百毫秒),更适合用MouseEnter(鼠标一进入就触发)和MouseLeave(鼠标离开就触发)
  3. 事件脚本块里直接引用$MyButton可能存在作用域问题,用$sender指代当前触发事件的控件更稳妥

完整实现代码

# 创建按钮实例
$MyButton = New-Object System.Windows.Forms.Button
$MyButton.FlatStyle = [System.Windows.Forms.FlatStyle]::Flat
$MyButton.Font = New-Object System.Drawing.Font("Roboto", 12,[System.Drawing.FontStyle]::Bold,[System.Drawing.GraphicsUnit]::Point, 0)
$MyButton.Location = New-Object System.Drawing.Point(5, 112)
$MyButton.Name = "MyButton"
$MyButton.Text = "My button"
$MyButton.Size = New-Object System.Drawing.Size(150, 40)

# 记录按钮默认的前景色和背景色,用于鼠标离开时恢复
$defaultForeColor = $MyButton.ForeColor
$defaultBackColor = $MyButton.BackColor

# 绑定鼠标进入事件:修改前景色与背景色
$MyButton.Add_MouseEnter({
    $sender = $args[0]
    $sender.ForeColor = [System.Drawing.Color]::White
    $sender.BackColor = [System.Drawing.Color]::Orange
})

# 绑定鼠标离开事件:恢复默认颜色
$MyButton.Add_MouseLeave({
    $sender = $args[0]
    $sender.ForeColor = $defaultForeColor
    $sender.BackColor = $defaultBackColor
})

# 测试用窗体(如需运行验证,保留以下代码)
$testForm = New-Object System.Windows.Forms.Form
$testForm.Controls.Add($MyButton)
$testForm.ShowDialog() | Out-Null

额外优化(针对Flat样式按钮)

如果你的按钮使用FlatStyle.Flat,还可以补充设置Flat外观的悬停高亮,让效果更完整:

$MyButton.FlatAppearance.MouseOverBackColor = [System.Drawing.Color]::DarkOrange

内容的提问来源于stack exchange,提问作者Tribun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 19:37:08