加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

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

发布时间:2020-12-14 01:39:47 所属栏目:Windows 来源:网络整理
导读:我有一个 WPF应用程序,主窗口的装饰是自定义的,通过WindowStyle =“无”.我绘制自己的标题栏和最小/最大/关闭按钮.不幸的是,当窗口调整大小时,Windows不强制我的MinWidth和MinHeight属性,因此允许将窗口调整到3×3(appx – 足够显示句柄来增长窗口). 我已经
我有一个 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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读