X

[WPF] 右上の閉じるボタンの無効化

[WPF] 右上の閉じるボタンの無効化

右上の閉じるボタンを無効化し、ダイアログWindowなどの誤閉じを防止する。

1)次のクラスを作成する。
Imports System.Windows.Interop
Public Class ClassNotClose
    <System.Runtime.InteropServices.DllImport(“user32.dll”)> _
    Shared Function GetSystemMenu(ByVal hWnd As IntPtr, _
                                  ByVal bRevert As Boolean) As IntPtr
    End Function

    <System.Runtime.InteropServices.DllImport(“user32.dll”)> _
    Shared Function EnableMenuItem(ByVal hWnd As IntPtr, _
                                   ByVal uIDEnableItem As UInteger, _
                                   ByVal uEnable As UInteger) As Boolean
    End Function

    Private Const MF_BYCOMMAND As UInteger = &H0
    Private Const MF_GRAYED As UInteger = &H1
    Private Const SC_CLOSE As UInteger = &HF060

    Private hwndSource As HwndSource = Nothing

    Public Sub DisEnable(winHndl As Object)
        Dim hwnd As IntPtr
        hwnd = DirectCast(PresentationSource.FromVisual(winHndl), HwndSource).Handle
        Dim hMenu As IntPtr = GetSystemMenu(hwnd, False)
        If hMenu <> IntPtr.Zero Then
            EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND Or MF_GRAYED)
        End If
    End Sub
End Class

2)閉じさせたくないWindowから呼び出す。(Loadedの中で等)
Dim oNotClose As New ClassNotClose
Private Sub Window2_Loaded(sender As Object, e As ystem.Windows.RoutedEventArgs) Handles Me.Loaded
        oNotClose.DisEnable(Me)
End Sub

itsysgroup:
Related Post