如何在WindowStyle =“None”的WPF窗口中执行MinWidth&MinHeight?

前端之家收集整理的这篇文章主要介绍了如何在WindowStyle =“None”的WPF窗口中执行MinWidth&MinHeight?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个 WPF应用程序,主窗口的装饰是自定义的,通过WindowStyle =“无”.我绘制自己的标题栏和最小/最大/关闭按钮.不幸的是,当窗口调整大小时,Windows不强制我的MinWidth和MinHeight属性,因此允许将窗口调整到3×3(appx – 足够显示句柄来增长窗口).

我已经不得不拦截窗口事件(sp.0x0024)来修复WindowStyle = none引起的最大化错误(在Windows任务栏中最大化).我不怕拦截更多的事件来实现我所需要的.

有没有人知道如何让我的窗口不能调整大小在我的MinWidth和MinHeight属性下,如果这是可能的?谢谢!!

你需要处理一个Windows消息来做,但这并不复杂.

你必须处理WM_WINDOWPOSCHANGING消息,这样在WPF中需要一些样板代码,你可以看到下面的实际逻辑只是两行代码.

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 them just change the pos
          // structure and set changedPos to true
          // ***********************

          // this is a simplified version that doesn't work in high-dpi settings
          // pos.cx and pos.cy are in "device pixels" and MinWidth and MinHeight 
          // are in "WPF pixels" (WPF pixels are always 1/96 of an inch - if your
          // system is configured correctly).
          if(pos.cx < MinWidth) { pos.cx = MinWidth; changedPos = true; }
          if(pos.cy < MinHeight) { pos.cy = MinHeight; changedPos = true; }


          // ***********************
          // end of "logic"
          // ***********************

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

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

   return IntPtr.Zero;
}
原文链接:https://www.f2er.com/windows/363833.html

猜你在找的Windows相关文章