How PInvoke can help

Problem: disabling the Close button

Sometimes, in an application, you want to have a window which has a control box (and thus an icon) that can be minimized and/or maximized, but cannot be closed. This requires a little work, but an important step is to disable the Close button in the top right of the window. In .NET you can set Form.ControlBox to false, but that will get rid of your minimize and maximize icons as well, which may not be what you want.

Disabled Close box
Desired effect: Close is disabled, but Minimize still works

In cases such as this one, it's necessary to "go native". To achieve this effect, we will need to disable the Close option on the system menu. When Windows renders the Close box in the non-client area, and handles clicks on it, it obeys the state of that menu item.

System menu with Close greyed out
The close option on the system menu needs to be greyed out as in this screenshot

Find a solution with

We will need to call two functions: GetSystemMenu and EnableMenuItem. In the latter case, we need to tell EnableMenuItem to find the menu item denoted by command SC_CLOSE, and make it either enabled or grayed out, as appropriate.

Since we don't know the exact syntax of the two signatures we are after, we can simply choose to insert them directly from Visual Studio, by clicking on our menu in Visual Studio.

The website suggests the following code:

GetSystemMenu signatures
PInvoke often offers both a C# signature and a VB signature
EnableMenuItem signature
C# signature for EnableMenuItem

Via the website, also lists appropriate constant values for EnableMenuItem, three of which are of particular interest:

Constant values for EnableMenuItem
Constant values for EnableMenuItem

We also need the constant value SC_CLOSE which, again, is easily found on by typing it into the search box:

internal const UInt32 SC_CLOSE = 0xF060;

We've now got all our pieces, which we can finally put together by writing code such as:

// Modify the close button for a form or other window.
public static void EnableCloseButton(IWin32Window window, bool bEnabled)
	IntPtr hSystemMenu = GetSystemMenu(window.Handle,false);

		(uint)(MF_BYCOMMAND | ( bEnabled ? MF_ENABLED : MF_GRAYED ) ));


This was an example illustrating how the resource and the Visual Studio add-in can help you find and insert tried and tested PInvoke signatures directly into your application.