How to disable <Alt + F4> and Window <Close> button in .NET

Posted by Admin L in .NET Programming on 20-06-2011. Tags:

Author: Nosa Lee
Original Address: https://www.seeksunslowly.com/disable-alt-f4-close
To reprint this article, please indicate the source, thank you.
_____________________________________

Sometimes, we need to disable <Alt + F4> keys and Window <Close> button, so as to prevent the window is closed abnormally. For instance: the progress window for backup data.

Through trial and summary, I found an easy but effective way to do it (VB 2008), and have not used API to avoid instability.
1. Create a new Windows Forms Application.
2. Put a Button on Form1 (Text = “Close Me”).
3. Double-click any place on Form1 in the Form Designer, replace all code as following:
[cc lang=”vbnet”]
Public Class Form1
‘ Can close form or not.
Private canClose As Boolean = False
Private Sub Me_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs) _
Handles Me.FormClosing
If Not canClose Then e.Cancel = True
End Sub

Private Sub Me_FormClosed(ByVal sender As Object, ByVal e As FormClosedEventArgs) _
Handles Me.FormClosed
Me.Dispose()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles Button1.Click
canClose = True
Me.Close()
End Sub
End Class
[/cc]
4. Run this program, you can find that <Alt + F4> keys and window <Close> button are inactive, only click <Close Me> can close the window.

Download the source codes
https://www.SeekSunSlowly.com/downloadable-source-codes/disable-alt-f4-close.zip

【赞赏 / Reward】

微信         支付宝         PayPal

Post a comment