WPF 窗口拖动/移动边界 [英] WPF Window Drag/Move Boundary

查看:46
本文介绍了WPF 窗口拖动/移动边界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是好奇您是否知道为窗口设置拖动边界的任何方法?

just curious if you know of any way to setup a drag boundary for a window?

拥有这些属性会很好:

Me.MinLeft = 10
Me.MinTop = 10
Me.MaxLeft = 150
Me.MaxTop = 150

我知道我可能会设置一个计时器,每 10 秒触发一次,然后检查左侧和顶部,然后在结束时将其移回.但让窗口表现得像撞墙一样不能走得更远,比如移动到屏幕边缘或类似的东西,会更优雅.

I know I could probably setup a timer to fire ever 10th of a second and check the left and top and then move it back if it's over. But it would be more elegant to have the window act like it hit a wall and can't go any farther, like moving to the edge of the screen or something similar.

某处似乎有些混乱,我想说明的是在上面的段落中,拖动而不是重新调整大小.

There seems to be some confusion somewhere, the point I'm trying to make is in the paragraph above, dragging, not re-sizing.

推荐答案

因为我毫不怀疑 Nir ​​的答案会奏效,花费一些时间来实现它,所以我能够用这段代码更优雅地做我想做的事:

As I have no doubt that Nir's answer will work spending a little time implementing it, I was able to do what I wanted a little bit more elegant with this code:

Private Sub myWindow_LocationChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LocationChanged

    Dim primaryBounds As System.Drawing.Rectangle = Windows.Forms.Screen.PrimaryScreen.Bounds
    Dim windowBounds As System.Drawing.Rectangle = New System.Drawing.Rectangle(CInt(Me.Left), CInt(Me.Top), CInt(Me.Width), CInt(Me.Height))

    If (windowBounds.Left < 0) Then
        windowBounds = New System.Drawing.Rectangle(0, windowBounds.Top, windowBounds.Width, windowBounds.Height)
    ElseIf (windowBounds.Right > primaryBounds.Right) Then
        windowBounds = New System.Drawing.Rectangle(primaryBounds.Right - windowBounds.Width, windowBounds.Top, windowBounds.Width, windowBounds.Height)
    End If

    If (windowBounds.Top < 0) Then
        windowBounds = New System.Drawing.Rectangle(windowBounds.Left, 0, windowBounds.Width, windowBounds.Height)
    ElseIf (windowBounds.Bottom > primaryBounds.Bottom) Then
        windowBounds = New System.Drawing.Rectangle(windowBounds.Left, primaryBounds.Bottom - windowBounds.Height, windowBounds.Width, windowBounds.Height)
    End If

    Me.Left = windowBounds.Left
    Me.Top = windowBounds.Top

End Sub

这使得被拖动的窗口停留在主屏幕(整个窗口)内,但您可以轻松地将边界更改为您需要的任何值.

This made the window being dragged stay within the primary screen (whole window), but you could easily change the bounds to whatever values you needed.

这篇关于WPF 窗口拖动/移动边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆