如何在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;
}

相关文章

Windows注册表操作基础代码 Windows下对注册表进行操作使用的...
黑客常用WinAPI函数整理之前的博客写了很多关于Windows编程的...
一个简单的Windows Socket可复用框架说起网络编程,无非是建...
Windows文件操作基础代码 Windows下对文件进行操作使用的一段...
Winpcap基础代码 使用Winpcap进行网络数据的截获和发送都需要...
使用vbs脚本进行批量编码转换 最近需要使用SourceInsight查看...