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

AwesomeWM 如何在代码中无需按回车/ESC关闭awful提示框

问题本质

按键触发后提示框未自动关闭的现象,和awful.prompt的组件设计逻辑直接相关:

  • keypressed_callback仅作为按键事件的监听钩子存在,在函数内写return只会终止单次回调的执行,完全不会影响awful.prompt本身的运行状态
  • awful.prompt默认的退出触发路径只有两个:用户按下回车键提交输入、用户按下ESC取消输入,除此之外组件会持续保持激活状态等待后续按键输入,这也是你按完y或其他任意键后,提示框仍长期存在的核心原因。
实现方案

要实现“第一次有效按键触发判断后立刻关闭提示框”的效果,不需要依赖返回值做流程控制,只需要在按键处理逻辑中主动调用awful.prompt.stop(),手动终止当前正在运行的提示流程即可。

修正后的完整代码片段

awful.key({ modkey, "Control", "Shift" }, "q",
    function ()
        awful.prompt.run {
            prompt       = "Shutdown? (y/n) ",
            textbox      = awful.screen.focused().mypromptbox.widget,
            keypressed_callback = function (_, key, _)
                -- 触发有效按键事件后,立刻终止当前激活的prompt
                awful.prompt.stop()
                -- 按键匹配后执行对应逻辑
                if key == "y" then
                    naughty.notify { text = "Shutting down!" }
                    -- 替换为你当前系统对应的关机指令
                    os.execute("systemctl poweroff")
                else
                    naughty.notify { text = "Not shutting down!" }
                end
            end,
        }
    end,
    {description = "shutdown", group = "awesome"}),

可选优化

如果不希望用户误触Ctrl、Shift、Super这类纯修饰键就直接关闭提示框,可以在停止prompt的逻辑前加一层判断,过滤掉无实际输入意义的按键:

keypressed_callback = function (_, key, _)
    -- 仅匹配单字符的实际输入键,跳过带上下后缀的修饰键(如Control_L、Shift_R)
    if #key == 1 then
        awful.prompt.stop()
        if key == "y" then
            naughty.notify { text = "Shutting down!" }
            os.execute("systemctl poweroff")
        else
            naughty.notify { text = "Not shutting down!" }
        end
    end
end,

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 17:57:05