WPF禁用窗口移动

时间:2010-03-08 11:10:11

标签: .net wpf

在wpf中如何通过拖动标题栏来阻止用户移动窗口?

1 个答案:

答案 0 :(得分:35)

由于您无法直接在WPF中定义WndProc,因此您需要获取HwndSource,并为其添加一个钩子:

public Window1()
{
    InitializeComponent();

    this.SourceInitialized += Window1_SourceInitialized;
}

private void Window1_SourceInitialized(object sender, EventArgs e)
{
    WindowInteropHelper helper = new WindowInteropHelper(this);
    HwndSource source = HwndSource.FromHwnd(helper.Handle);
    source.AddHook(WndProc);    
}

const int WM_SYSCOMMAND = 0x0112;
const int SC_MOVE = 0xF010;

private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam,  ref bool handled)
{

   switch(msg)
   {
      case WM_SYSCOMMAND:
          int command = wParam.ToInt32() & 0xfff0;
          if (command == SC_MOVE)
          {
             handled = true;
          }
          break;
      default:
          break;
   }
   return IntPtr.Zero;
}