使用 Win32 API,您可以通过以下方式做到这一点:
[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);
}
您需要使用 GetClassLong / SetClassLong 来启用 CS_NOCLOSE 样式。然后您可以使用相同的操作将其删除,只需在 SetClassLongPtr 中使用 (style & ~CS_NOCLOSE)。
实际上,您也可以在 WPF 应用程序中执行此操作(是的,我知道,问题是关于 WinForms,但也许有一天有人会需要它):
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);
}
不过,您应该考虑其他人的建议:只显示一个 MessageBox 或其他类型的消息来指示用户现在不应该关闭窗口。
编辑:
由于窗口类只是一个 UINT,您可以使用 GetClassLong 和 SetClassLong 函数而不是 GetClassLongPtr 和 SetClassLongPtr(如 MSDN 所述):
如果您正在检索指针或句柄,则此函数已被 GetClassLongPtr 函数取代。 (指针和句柄在 32 位 Windows 上为 32 位,在 64 位 Windows 上为 64 位。)
这解决了 Cody Gray 描述的关于 32 位操作系统中缺少 *Ptr 函数的问题。