how to prevent using ALT F4 TO close a vb form

Dani AI

Generated

gave a quick, practical fix by handling form-level key events. That works when the form actually receives the KeyDown, but Alt+F4 is a system close sequence (it ends up as a WM_CLOSE / system close command), so a key handler alone can be unreliable in some focus/modal scenarios. (learn.microsoft.com)

A safe, simple pattern is to cancel the close in the FormClosing event when closure should be blocked (for example during a critical operation). The FormClosingEventArgs exposes Cancel and CloseReason so the close can be rejected only for user-initiated closes: (learn.microsoft.com)

Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
    If e.CloseReason = CloseReason.UserClosing AndAlso isCriticalOperation Then
        e.Cancel = True
    End If
End Sub

For the most robust interception (blocks Alt+F4 and the title-bar Close), override WndProc and ignore the system close command (WM_SYSCOMMAND / SC_CLOSE). This prevents the system close message from reaching default processing — use it sparingly because it also blocks ordinary window-close behavior: (learn.microsoft.com)

Protected Overrides Sub WndProc(ByRef m As Message)
    Const WM_SYSCOMMAND As Integer = &H112
    Const SC_CLOSE As Integer = &HF060

    If m.Msg = WM_SYSCOMMAND AndAlso (m.WParam.ToInt32() And &HFFF0) = SC_CLOSE Then
        Return   ' swallow the close request
    End If

    MyBase.WndProc(m)
End Sub

Notes: a common hybrid is to set a boolean flag when a key handler detects Alt+F4 and then cancel in FormClosing; KeyPreview still helps for many cases but won’t catch system-level messages in every situation. Consider user experience and accessibility before permanently disabling standard OS behaviors. Thread note: asked to mark solved where appropriate.

Recommended Answers

All 2 Replies

The Alt+F4 can be disabled by setting the KeyPreview of the Form to true and adding a KeyDown event handler

Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
        If e.KeyCode = Keys.F4 And e.Modifiers = Keys.Alt Then
            e.Handled = True
        End If
    End Sub

Mark Question Solved please

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.