在WPF編程中,可能需要去除窗口的右上角的幾個按鈕:最大化按鈕、最小化按鈕和關閉按鈕,其他幾個都很好處理,就是這個關閉按鈕,WPF模型不提供刪除或隱藏功能,我們只有採用一些非正常手段,比如使用Win32函數,比如禁用,對於禁用關閉功能,可以重載OnClosing()函數來實現,——使用戶無法通過點擊右上角的關閉按鈕來關閉窗口:
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true;
}
另一種方法就比較麻煩了,但是也是最徹底的方法:去除關閉按鈕
首先,在你的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);
然後,在裝載事件中加入:
var hwnd = new WindowInteropHelper(this).Handle;
SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU);
但是這種情況下用戶仍然可以通過Alt+F4關閉窗口,所以你可能仍然需要實現上面所說的重載OnClosing()函數,將其禁用。