We're having some problems with our phones at the moment. You can contact sales on sales@red-gate.com, or visit our support center.

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 PInvoke.net

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 PInvoke.net menu in Visual Studio.

The PInvoke.net 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, PInvoke.net 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 PInvoke.net 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 PInvoke.net resource and the PInvoke.net Visual Studio add-in can help you find and insert tried and tested PInvoke signatures directly into your application.