*****C# Winform 屏蔽窗口的关闭按钮

來源:

http://hi.baidu.com/%CD%F5%D5%DF%CA%D3%BD%E7%CA%FD%BE%DD%D6%D0%D0%C4/blog/item/324bcddbac4f20e239012f90.html

今天在做Winform登陆框时想到了一个问题,每次做需要登录的软件时都必须在 窗体的Closed事件中判断是否已经成功登陆,以防止非法用户通过关闭登陆框而进入软件系统,的确是挺麻烦的,要是能把窗体的关闭按钮给屏蔽了 那就能更省事了不是?呵呵 ,在网上找了找还真找到了 ,与大家分享啊~~~

添加引用 using System.Runtime.InteropServices;

然后将下面的代码写入工程里面

        private const int SC_CLOSE = 0xF060;
        private const int MF_ENABLED = 0x00000000;
        private const int MF_GRAYED = 0x00000001;
        private const int MF_DISABLED = 0x00000002;
        [DllImport("user32.dll", EntryPoint = "GetSystemMenu")]
        private static extern IntPtr GetSystemMenu(IntPtr hWnd, int bRevert);
        [DllImport("User32.dll")]
        public static extern bool EnableMenuItem(IntPtr hMenu, int uIDEnableItem, int uEnable);

再将下面代码写在页面的Load事件中就ok啦

        IntPtr hMenu = GetSystemMenu(this.Handle, 0);
        EnableMenuItem(hMenu, SC_CLOSE, MF_DISABLED | MF_GRAYED);

呵呵,是不是挺简单的!

还有一种不用判断窗体Closed 的方法:

        protected override void WndProc(ref   Message m)
        {
            const int WM_SYSCOMMAND = 0x0112;
            const int SC_CLOSE = 0xF060;
            if (m.Msg == WM_SYSCOMMAND && (int)m.WParam == SC_CLOSE)
            {   
                Application.Exit();
                return;
            }
            base.WndProc(ref   m);
        }

也挺好用的!

你可能感兴趣的:(WinForm)