WPF Window 仅垂直拖动
WPF Window Drag vertically only
我制作了一个跨越整个屏幕宽度的自定义覆盖消息框(归结为无边框 WPF window)。然而,我已经为用户实现了能够拖动消息框的逻辑,因为您可以将其配置为 bot 是一个覆盖层,而是一个正常大小的消息框。
对于叠加层,我想将拖动移动限制为仅包括垂直 (up/down) 变化,window 应该不能水平拖动。
我将 MouseDown 事件连接到 window 中的边框,以便将 window 拖到周围:
private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) {
if (msgType != MessageType.OverlayMessage && msgType != MessageType.OverlayMessageDialog) {
this.DragMove(); // drags the window normally
}
}
我尝试的是在鼠标按下事件上捕获光标,在 MouseMove 事件中执行拖动逻辑并在释放鼠标按钮时释放光标,但这不起作用 - 当我单击边框时,然后单击其他内容(远离 window)并返回到边框,然后 window 会按我想要的方式捕捉到光标(仅垂直移动),但这种行为应该发生在我单击并拖动光标:
bool inDrag = false;
Point anchorPoint;
private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) {
anchorPoint = PointToScreen(e.GetPosition(this));
inDrag = true;
CaptureMouse();
e.Handled = true;
}
private void Border_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) {
if (inDrag) {
ReleaseMouseCapture();
inDrag = false;
e.Handled = true;
}
}
private void Border_MouseMove(object sender, MouseEventArgs e) {
if (inDrag) {
Point currentPoint = PointToScreen(e.GetPosition(this));
this.Top = this.Top + currentPoint.Y - anchorPoint.Y; // only allow vertical movements
anchorPoint = currentPoint;
}
}
将以下内容添加到您的鼠标移动中:
if (e.LeftButton != MouseButtonState.Pressed) return;
另外,听起来好像有其他东西吞没了您的 MouseUp 事件。您是在处理 PreviewMouseDown/Up 还是只是 MouseDown/Up - 您可以尝试使用前者来获取隧道事件。
我制作了一个跨越整个屏幕宽度的自定义覆盖消息框(归结为无边框 WPF window)。然而,我已经为用户实现了能够拖动消息框的逻辑,因为您可以将其配置为 bot 是一个覆盖层,而是一个正常大小的消息框。
对于叠加层,我想将拖动移动限制为仅包括垂直 (up/down) 变化,window 应该不能水平拖动。
我将 MouseDown 事件连接到 window 中的边框,以便将 window 拖到周围:
private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) {
if (msgType != MessageType.OverlayMessage && msgType != MessageType.OverlayMessageDialog) {
this.DragMove(); // drags the window normally
}
}
我尝试的是在鼠标按下事件上捕获光标,在 MouseMove 事件中执行拖动逻辑并在释放鼠标按钮时释放光标,但这不起作用 - 当我单击边框时,然后单击其他内容(远离 window)并返回到边框,然后 window 会按我想要的方式捕捉到光标(仅垂直移动),但这种行为应该发生在我单击并拖动光标:
bool inDrag = false;
Point anchorPoint;
private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) {
anchorPoint = PointToScreen(e.GetPosition(this));
inDrag = true;
CaptureMouse();
e.Handled = true;
}
private void Border_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) {
if (inDrag) {
ReleaseMouseCapture();
inDrag = false;
e.Handled = true;
}
}
private void Border_MouseMove(object sender, MouseEventArgs e) {
if (inDrag) {
Point currentPoint = PointToScreen(e.GetPosition(this));
this.Top = this.Top + currentPoint.Y - anchorPoint.Y; // only allow vertical movements
anchorPoint = currentPoint;
}
}
将以下内容添加到您的鼠标移动中:
if (e.LeftButton != MouseButtonState.Pressed) return;
另外,听起来好像有其他东西吞没了您的 MouseUp 事件。您是在处理 PreviewMouseDown/Up 还是只是 MouseDown/Up - 您可以尝试使用前者来获取隧道事件。