在wpf中,我如何防止用户通过拖动标题栏移动窗口?
由于在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;
}
这是一个很老的帖子,虽然现在也有其他技术如UWP和WinUI3,但我的建议或许对其他人也有所帮助。
我通过设置来达到目标:
WindowStyle="None"
IsCancel="True"
就是这样,不需要互操作代码。最小化的代码。