Hide the close button of a WPF window

In a WPF application that I am currently working with, I have to be able to hide the close button of a progress window. Instead of being closed by the user (like an alert window or message box), this progress window should instead be closed by its owner window once its related operation has finished.

So, how do you hide the close button. There is no such property (at least, I do not find one), so it seems to me that you have to roll up your sleeves and do some DLL import goodness 🙂

First of all, define two constanst and two methods:

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);

Then, in the window class, call the imported DLL methods as such:

var hwnd = new WindowInteropHelper(this).Handle;
   SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU);

Naturally, the most convenient way to achieve this is to wrap the functionality within an extension method:

public static class WindowExtensions
   {
      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);

      public static void HideCloseButton(this Window window)
      {
         var hwnd = new WindowInteropHelper(window).Handle;
         SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU);
      }
   }

If you know a more convenient way to hide the close button (maybe I just did not find a native property/method that actually exists?), please indulge me.

 

Advertisements