如何在表单中单击“X”,不会将其关闭但隐藏它

时间:2010-07-14 18:24:28

标签: c# vb.net

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

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

感谢。

3 个答案:

答案 0 :(得分:4)

只需实现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

答案 1 :(得分:3)

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

答案 2 :(得分:1)

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