1、新建一个Windows应用程序,新建一个窗体,进入代码视图。
2、添加必要的命名空间:
using
System.Runtime.InteropServices;
3、添加必要的常数和API函数的引用:
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);
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);
4、在窗体的Load事件处理函数内添加代码:
IntPtr hMenu
=
GetSystemMenu(
this
.Handle,
0
);
EnableMenuItem(hMenu, SC_CLOSE, MF_DISABLED | MF_GRAYED);
EnableMenuItem(hMenu, SC_CLOSE, MF_DISABLED | MF_GRAYED);
下面是效果图:
![](https://i-blog.csdnimg.cn/blog_migrate/6a27061a4d883e634c6afc75915931f9.jpeg)
那么如果该关键进程结束,需要使该按钮可用怎么办?
使用下面的代码就可以了:
IntPtr hMenu
=
GetSystemMenu(
this
.Handle,
0
);
EnableMenuItem(hMenu, SC_CLOSE, MF_ENABLED);
EnableMenuItem(hMenu, SC_CLOSE, MF_ENABLED);
在 http://ryanfarley.com/blog/archive/2004/04/12/526.aspx中介绍了另一种做法,也可以参考一下。