c# - 如何在WPF窗口中隐藏关闭按钮?

标签 c# wpf xaml button dialog

我正在 WPF 中编写一个模式对话框。如何将 WPF 窗口设置为没有关闭按钮?我仍然希望它的 WindowState 有一个正常的标题栏。

我找到了 ResizeModeWindowStateWindowStyle,但这些属性都不允许我隐藏关闭按钮但显示标题栏,如在模态对话框中。

最佳答案

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/

相关文章:

c# - AdDuplex 的 Adrotator 问题

xaml - 网格中一行的用户控件

c# - 如何在 xamarin.android 中使用 HttpClient 将数据传递到服务器

c# - Path.GetExtension(file.FileName) 给出可能的 Nullreference 警告

c# - 仅在 Teamcity 上测试失败

c# - 如何使用MVVM在ListBox中显示字符串?

wpf - DataGrid 大小调整问题

c# - Awesomium.NET 在调整大小时崩溃 - 内存泄漏

wpf - 覆盖 Silverlight 4 中的默认 ItemsPanelTemplate?

c# - 谁能指出任何好的 MVP 文章/教程的方向?