欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

WPF禁止窗口缩放和移动

程序员文章站 2022-07-13 23:19:25
...

1、xaml中设置窗口不能改变大小, ResizeMode=“NoResize”。虽然设置不能改变大小,但是双击窗口标题窗口仍然会变小;窗口标题点击左键移动鼠标,窗口也会进行缩放。

2、需要拦截WPF窗口的双击事件、移动事件

//窗口初始化后指定钩子函数
ntPtr hwnd = new WindowInteropHelper(this).Handle;
HwndSource.FromHwnd(hwnd).AddHook(new HwndSourceHook(WndProc));


//钩子函数的实现
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
      //拦截标题栏双击和窗口移动事件
     if (msg == 0x00A3 || msg == 0x0003|| wParam == (IntPtr)0xF012)           
     {
         handled = true;
         wParam = IntPtr.Zero;
     }
      return IntPtr.Zero;
 }

3、前两步做完之后,窗体不会缩放了,但是点击窗口左上角图标仍然会出现系统菜单里面有移动选项,因此需要从系统菜单中将移动移除。

 [DllImport("user32.dll", EntryPoint = "GetSystemMenu")]
  private static extern IntPtr GetSystemMenu(IntPtr hwnd, int revert);
  
    [DllImport("user32.dll", EntryPoint = "RemoveMenu")]
    private static extern int RemoveMenu(IntPtr hmenu, int npos, int wflags);
    
    [DllImport("user32.dll", EntryPoint = "GetMenuItemCount")]
    private static extern int GetMenuItemCount(IntPtr hmenu);

    [DllImport("user32.dll", EntryPoint = "GetMenuStringW", CharSet = CharSet.Unicode)]
    private static extern int GetMenuString(IntPtr hMenu, 
        uint uIDItem,StringBuilder lpString,  int cchMax,  uint flags);
 
 	//常量
    private const int MF_BYPOSITION = 0x0400;
    private const int MF_DISABLED = 0x0002;


        private void FlashCurveWnd_SourceInitialized(object sender, EventArgs e)
        {
            IntPtr handle = new WindowInteropHelper(this).Handle;
            IntPtr hmenu = GetSystemMenu(handle, 0);
            int cnt = GetMenuItemCount(hmenu);
            for (int i = cnt - 1; i >= 0; i--)
            {
                StringBuilder tmpstr = new StringBuilder(100);
                GetMenuString(hmenu, (uint)i, tmpstr, 255, MF_DISABLED | MF_BYPOSITION);
                if (tmpstr.ToString().Contains("移动"))
                {
                    RemoveMenu(hmenu, i, MF_DISABLED | MF_BYPOSITION);
                }                
            }
        }


至此,所有的窗口缩放和移动操作都被屏蔽掉了。

相关标签: C#