【问题标题】:How to Clicking "X" in Form, will not close it but hide it如何在表单中单击“X”,不会关闭它而是隐藏它
【发布时间】:2010-07-14 18:24:27
【问题描述】:

当用户单击表单上的“X”按钮时,如何使我的表单不关闭而是隐藏?

因为我有一个包含退出菜单的 NotifyIcon,该菜单实际上执行表单关闭(我不希望表单的“X”关闭表单而是隐藏它)。

谢谢。

【问题讨论】:

  • close 释放表单,而 hide 使其不可见并保持状态
  • 是的,删除了之前的评论。我在考虑 DialogResult。

标签: c# vb.net


【解决方案1】:

只需实现 FormClosing 事件。取消关闭并隐藏表单,除非它是由通知图标的上下文菜单触发的。例如:

    Private CloseAllowed As Boolean

    Protected Overrides Sub OnFormClosing(ByVal e As System.Windows.Forms.FormClosingEventArgs)
        If Not CloseAllowed And e.CloseReason = CloseReason.UserClosing Then
            Me.Hide()
            e.Cancel = True
        End If
        MyBase.OnFormClosing(e)
    End Sub

    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        CloseAllowed = True
        Me.Close()
    End Sub

【讨论】:

  • 如果您只是从工具条项中调用 Application.Exit(),则不需要 CloseAllowed。
  • 很好,我将其更改为 Application.Exit()。感谢您的提示。
【解决方案2】:

您需要处理 Form.Closing 事件并将 e.Cancel 设置为 true 以阻止表单关闭。要隐藏它,请调用Hide 方法。

【讨论】:

  • 好的,我已经设置了 e.Cancel=True 但如果我想真正关闭表单,那该怎么办?就像使用菜单 Exit 来关闭表单一样。
  • @jameslcs - 只需从工具条项单击处理程序中调用 Application.Exit() 并检查 FormClosing 事件处理程序中的 e.CloseReason。
【解决方案3】:
Private Sub Form2_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        e.Cancel = True
        Me.Hide()

End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-02
    • 1970-01-01
    • 1970-01-01
    • 2018-08-24
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    相关资源
    最近更新 更多