我正在 WPF 中编写一个模式对话框。如何将 WPF 窗口设置为没有关闭按钮?我仍然希望它的 WindowState
有一个正常的标题栏。
我找到了 ResizeMode
、WindowState
和 WindowStyle
,但这些属性都不允许我隐藏关闭按钮但显示标题栏,如在模态对话框中。
最佳答案
WPF 没有内置属性来隐藏标题栏的关闭按钮,但您可以通过几行 P/Invoke 来实现。
首先,将这些声明添加到您的 Window 类中:
private const int GWL_STYLE = -16;
private const int WS_SYSMENU = 0x80000;
[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
然后将此代码放入窗口的 Loaded
事件中:
var hwnd = new WindowInteropHelper(this).Handle;
SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU);
就这样:不再有“关闭”按钮。标题栏左侧也不会出现窗口图标,这意味着即使右键单击标题栏,也不会出现系统菜单 - 它们都在一起。
重要提示:这只是隐藏按钮。用户仍然可以关闭窗口!如果用户按 Alt+F4,或通过任务栏关闭应用程序,窗口仍会关闭。
如果您不想让窗口在后台线程完成之前关闭,那么您也可以重写 OnClosing
并将 Cancel
设置为 true,如 Gabe建议。
关于c# - 如何在WPF窗口中隐藏关闭按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/743906/