我有一个没有边框的表单,我希望用户能够移动它。我还没有找到任何可以让我这样做的东西。
是否可以移动边框设置为无的窗口?
引入一个布尔变量,如果表单当前被拖动,则该变量保存状态,以及保存拖动起点的变量。然后 OnMove 相应地移动表单。由于这已经在其他地方得到了回答,我只是复制并粘贴到这里。
Class Form1
Private IsFormBeingDragged As Boolean = False
Private MouseDownX As Integer
Private MouseDownY As Integer
Private Sub Form1_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles MyBase.MouseDown
If e.Button = MouseButtons.Left Then
IsFormBeingDragged = True
MouseDownX = e.X
MouseDownY = e.Y
End If
End Sub
Private Sub Form1_MouseUp(ByVal sender As Object, ByVal e As MouseEventArgs) Handles MyBase.MouseUp
If e.Button = MouseButtons.Left Then
IsFormBeingDragged = False
End If
End Sub
Private Sub Form1_MouseMove(ByVal sender As Object, ByVal e As MouseEventArgs) Handles MyBase.MouseMove
If IsFormBeingDragged Then
Dim temp As Point = New Point()
temp.X = Me.Location.X + (e.X - MouseDownX)
temp.Y = Me.Location.Y + (e.Y - MouseDownY)
Me.Location = temp
temp = Nothing
End If
End Sub
End Class
从http://www.dreamincode.net/forums/topic/59643-moving-form-with-formborderstyle-none/偷来的
所有“简单”的 VB 答案都让我的表单在多个屏幕上跳跃。所以我从 C# 中的相同答案中得出这个,它就像一个魅力:
Public Const WM_NCLBUTTONDOWN As Integer = 161
Public Const HT_CAPTION As Integer = 2
然后
<DllImport("User32")> Private Shared Function SendMessage(hWnd As IntPtr, Msg As Integer, wParam As Integer, lParam As Integer) As Integer
End Function
<DllImport("User32")> Private Shared Function ReleaseCapture() As Boolean
End Function
最后
Private Sub Form1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseDown
If (e.Button = MouseButtons.Left) Then
ReleaseCapture()
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0)
End If
End Sub
另一种方法是处理WM_NCHITTEST
消息。这使您可以让表单的某些部分响应鼠标事件,就像标题栏、边框等对带边框的窗口一样。例如,如果您的表单上有一个标签并且您HTCAPTION
在WM_NCHITTEST
处理程序中返回,您将能够通过拖动此标签来移动表单,就像您可以通过拖动其标题栏来移动常规窗口一样。有关示例代码,请参阅此Stack Overflow 问题。
Dim offSetX As Integer
Dim offSetY As Integer
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Me.Location = New Point(Cursor.Position.X - offSetX, Cursor.Position.Y - offSetY)
End Sub
Private Sub Form1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseDown
offSetX = PointToClient(Cursor.Position).X
offSetY = PointToClient(Cursor.Position).Y
Timer1.Enabled = True
End Sub
Private Sub Form1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseUp
Timer1.Enabled = False
End Sub
这是一种有点邋遢的做法 xD
希望它有所帮助=]