Sunday, April 12, 2009

Hiding / Disabling Maximize and/or Minimize Box in WPF

After trying my hands on the WPF, I realized that I could convert my existing Windows Forms applications into rich looking WPF applications. The task of migration was definitely not easy. During the course of migration, I came across many hurdles and seemed it was impossible to achieve in WPF. But thanks to the msdn help, which made a lot of things easier :-)
Since I was converting my existing application, I started looking for the similar features in WPF. The problem I faced was in the initial phase itself where I wanted to disable MaximizeBox button in WPF. This posed a challenge to me since I had no clue as to how to achieve this. After searching the net for a while, I got a solution which I will share with you all to make your life easier.
Disabling Maximize Box Button on the WPF Window:
This can be done as follows: Put this piece of code above the main class.


internal static class WindowExtensions

{
[DllImport("user32.dll")]
internal extern static int SetWindowLong(IntPtr hwnd, int index, int value);
[DllImport("user32.dll")] internal extern static int GetWindowLong(IntPtr hwnd, int index);
internal static void DisableMaximizeButton(this Window window)
{
const int GWL_STYLE = -16;
IntPtr hwnd = new System.Windows.Interop.WindowInteropHelper(window).Handle;
long value = GetWindowLong(hwnd, GWL_STYLE);
SetWindowLong(hwnd, GWL_STYLE, (int)(value & -65537));
}
}
This will disable the MaximizeBox; call it from the form’s constructor.
this.DisableMaximizeButton();

However, I found that calling
DisableMaximizeButton(); directly from the form’s constructor does not work. So here is the work around I found in one of the forums. Put it in the form’s constructor this way.
this.SourceInitialized += (x, y) =>

{
this.DisableMaximizeButton();
};
Disabling Minimize Box Button on the WPF Window:
Above piece of code can be used with the slight modification to the below line. Instead of -65537, use -131073.
SetWindowLong(hwnd, GWL_STYLE, (int)(value & -131073));
And if you wish to hide both MaximizeBox and MinimizeBox buttons, you can do it this way:
SetWindowLong(hwnd, GWL_STYLE, (int)(value & -131073 & -65537));

I hope this will help you :-)
Cheers!