Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to disable alt+F4 for the application?

Tags:

c#

.net

winforms

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?

like image 233
mchicago Avatar asked Oct 15 '12 15:10

mchicago


1 Answers

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;
        }
    }
}
like image 97
Simon Mourier Avatar answered Oct 03 '22 21:10

Simon Mourier