如何禁用ALT + F4应用程序?应用程序、ALT

2023-09-03 03:15:14 作者:你抓不住萌萌哒

我怎么能禁止使用 ALT + F4 应用程序范围内对C#应用程序?

How can I disable the use of ALT+F4 application-wide for C# applications?

在我的应用程序,我有很多的WinForms,我想禁用关闭使用 ALT + F4 形式的能力。用户应该能够关闭使用的形式为X,虽然形式。

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.

再次,这是不只是一种形式。我正在寻找一种方式,使 ALT + F4 是整个应用程序禁用,将不承担任何形式的合作。这可能吗?

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;
        }
    }
}