maandag 4 februari 2008

Hoe schakel je de 'X' knop van een Windows Form uit in C#

De sluitknop ('X' knop) van een Windows form kan je niet zomaar uitschakelen (disablen) in C#. Hiervoor dien je een aantal API calls uit te voeren. Hieronder een stukje voorbeeldcode:

private const int MF_BYPOSITION = 0x400;

[DllImport("user32.Dll")]
public static extern IntPtr RemoveMenu(IntPtr hMenu, int nPosition, int wFlags);

[DllImport("User32.Dll")]
public static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);

[DllImport("User32.Dll")]
public static extern IntPtr GetMenuItemCount(IntPtr hMenu);

/// <summary>
/// Disables the close button of a windows form
/// </summary>
/// <param name="hwnd">The handle of the form.</param>
public static void DisableCloseButton(IntPtr hwnd)
{
//Obtain the handle to the form's system menu
IntPtr menu = GetSystemMenu(hwnd, false);

// Get the count of the items in the system menu
IntPtr menuItemCount = GetMenuItemCount(menu);

// Remove the close menuitem
RemoveMenu(menu, menuItemCount.ToInt32() - 1, MF_BYPOSITION);
}

Geen opmerkingen: