Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I Only Allow Uniform Resizing in a WPF Window?

I don't want my window to be resized either "only horizontally" or "only vertically." Is there a property I can set on my window that can enforce this, or is there a nifty code-behind trick I can use?

like image 779
Mark Carpenter Avatar asked Dec 22 '08 15:12

Mark Carpenter


People also ask

How do I resize a control in WPF?

In WPF, you can create a resizable shape by using the Path control. Simply set up your shape's path data and then set the Stretch property to Fill and your shape will resize itself to fit the space available.

What is WPF viewbox?

The Viewbox control is used to stretch or scale a child element.

How do I center a WPF window?

Centring Windows To open a new window and have it centred on the screen, set the WindowStartupLocation property to CenterScreen. You can do this using the XAML or in code before the window is displayed. Run the program and click the button to see the result.


1 Answers

You can always handle the WM_WINDOWPOSCHANGING message, this let's you control the window size and position during the resizing process (as opposed to fixing things after the user finished resizing).

Here is how you do it in WPF, I combined this code from several sources, so there could be some syntax errors in it.

internal enum WM
{
   WINDOWPOSCHANGING = 0x0046,
}

[StructLayout(LayoutKind.Sequential)]
internal struct WINDOWPOS
{
   public IntPtr hwnd;
   public IntPtr hwndInsertAfter;
   public int x;
   public int y;
   public int cx;
   public int cy;
   public int flags;
}

private void Window_SourceInitialized(object sender, EventArgs ea)
{
   HwndSource hwndSource = (HwndSource)HwndSource.FromVisual((Window)sender);
   hwndSource.AddHook(DragHook);
}

private static IntPtr DragHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handeled)
{
   switch ((WM)msg)
   {
      case WM.WINDOWPOSCHANGING:
      {
          WINDOWPOS pos = (WINDOWPOS)Marshal.PtrToStructure(lParam, typeof(WINDOWPOS));
          if ((pos.flags & (int)SWP.NOMOVE) != 0)
          {
              return IntPtr.Zero;
          }

          Window wnd = (Window)HwndSource.FromHwnd(hwnd).RootVisual;
          if (wnd == null)
          {
             return IntPtr.Zero;
          }

          bool changedPos = false;

          // ***********************
          // Here you check the values inside the pos structure
          // if you want to override tehm just change the pos
          // structure and set changedPos to true
          // ***********************

          if (!changedPos)
          {
             return IntPtr.Zero;
          }

          Marshal.StructureToPtr(pos, lParam, true);
          handeled = true;
       }
       break;
   }

   return IntPtr.Zero;
}
like image 104
Nir Avatar answered Oct 09 '22 00:10

Nir