How can I disable the use of ALT+F4 application-wide for C# applications?
In my application, I have many WinForms and I want to disable the ability of closing the forms using ALT+F4. Users should be able to close the form using "X" of the form though.
Again this is not for just one form. I am looking for a way so ALT+F4 is disabled for the entire application and will not work for any of the form. Is it possible?
You could put something like this in the main startup method:
namespace WindowsFormsApplication1
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.AddMessageFilter(new AltF4Filter()); // Add a message filter
Application.Run(new Form1());
}
}
public class AltF4Filter : IMessageFilter
{
public bool PreFilterMessage(ref Message m)
{
const int WM_SYSKEYDOWN = 0x0104;
if (m.Msg == WM_SYSKEYDOWN)
{
bool alt = ((int)m.LParam & 0x20000000) != 0;
if (alt && (m.WParam == new IntPtr((int)Keys.F4)))
return true; // eat it!
}
return false;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With