Using the Win32 API, you can do this as follows:
[DllImport("User32.dll")] private static extern uint GetClassLong(IntPtr hwnd, int nIndex); [DllImport("User32.dll")] private static extern uint SetClassLong(IntPtr hwnd, int nIndex, uint dwNewLong); private const int GCL_STYLE = -26; private const uint CS_NOCLOSE = 0x0200; private void Form1_Load(object sender, EventArgs e) { var style = GetClassLong(Handle, GCL_STYLE); SetClassLong(Handle, GCL_STYLE, style | CS_NOCLOSE); }
You will need to use GetClassLong / SetClassLong to enable the CS_NOCLOSE style. Then you can delete it using the same operations, just use (style and ~ CS_NOCLOSE) in SetClassLongPtr.
Actually, you can do this in WPF applications too (yes, I know, the question is about WinForms, but maybe someone will need it):
private void MainWindow_OnLoaded(object sender, RoutedEventArgs e) { var hwnd = new WindowInteropHelper(this).Handle; var style = GetClassLong(hwnd, GCL_STYLE); SetClassLong(hwnd, GCL_STYLE, style | CS_NOCLOSE); }
However, you should think about what others have suggested: just show a MessageBox or another message to indicate that the user should not close the window right now.
Edit: Since the window class is only UINT, you can use the GetClassLong and SetClassLong functions instead of GetClassLongPtr and SetClassLongPtr (as MSDN says):
If you are retrieving a pointer or handle, this function has been replaced by the GetClassLongPtr function. (Pointers and descriptors are 32 bits on 32-bit Windows and 64 bits on 64-bit Windows.)
This solves the problem described by Cody Gray regarding the lack of * Ptr functions in a 32-bit OS.