65.9K
CodeProject 正在变化。 阅读更多。
Home

运行时轻松拖放控件

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.60/5 (9投票s)

2009年7月16日

CPOL

1分钟阅读

viewsIcon

65339

downloadIcon

3464

允许用户自定义您的窗体

CPdragNdrop_small.GIF

引言

我发现了一些文章展示了如何在运行时允许拖放控件,但大多数要么过于复杂,要么比必要的难度大得多。

免责声明

这是我在 CodeProject 上的第一篇文章,请多多包涵!目前,这不是实现此功能的最佳和最安全的方法,但(我相信)是最简单的方法。我已经在几个程序中使用过这种方法,并且没有任何问题,但我相信你们会发现一些问题。:)

它是什么以及不是什么

示例包含一个非常简单的演示,展示了最基本的结果,并且可以在我的签名中的链接中找到逐步说明。代码很简单,我相信文章也应该如此,所以我将一次性发布所有代码。

 Public Class Form1
    Dim dragging As Boolean
    Dim startX As Integer
    Dim startY As Integer
    Private Sub Form1_Load(ByVal sender As System.Object, _
		ByVal e As System.EventArgs) Handles MyBase.Load
        'TODO: This line of code loads data into the 
        ''NorthwindDataSet.Employees' table. You can move, or remove it, as needed.
        Me.EmployeesTableAdapter.Fill(Me.NorthwindDataSet.Employees)
        For Each Control As Control In Me.Controls
            AddHandler Control.MouseDown, AddressOf startDrag
            AddHandler Control.MouseMove, AddressOf whileDragging
            AddHandler Control.MouseUp, AddressOf endDrag
        Next
        For Each Control As Control In Me.Controls
            For Each item In My.Settings.controlLocations
                If Split(item, "!")(0) = Control.Name Then
                    Control.Location = New Point(Split(item, "!")(1), _
						Split(item, "!")(2))
                End If
            Next
        Next
    End Sub
    Private Sub startDrag(ByVal sender As Object, _
		ByVal e As System.Windows.Forms.MouseEventArgs)
        dragging = True
        startX = e.X
        startY = e.Y
    End Sub
    Private Sub whileDragging(ByVal sender As System.Object, _
		ByVal e As System.Windows.Forms.MouseEventArgs)
        If dragging = True Then
            sender.Location = New Point(sender.Location.X + _
		e.X - startX, sender.Location.Y + e.Y - startY)
            Me.Refresh()
        End If
    End Sub
    Private Sub endDrag(ByVal sender As System.Object, ByVal e As System.EventArgs)
        dragging = False
        My.Settings.controlLocations.Clear()
        For Each Control As Control In Me.Controls
            My.Settings.controlLocations.Add(Control.Name & "!" _
		& Control.Location.X & "!" & Control.Location.Y)
        Next
        My.Settings.Save()
    End Sub
End Class

代码的作用

这 3 个 sub 完成了所有工作,并且有一个名为 controlLocations 的空白 My.Settings,用于存储位置,否则每次表单都会重置。为了保持简单,我没有包含一些你可能想要的功能

  • 一个用于启用或禁用拖动功能的按钮
  • 一种指定仅允许移动某些类型控件的方法

如果有请求,我可以添加这些功能。

关注点

  • 快速且简单

历史

  • 2009 年 7 月 16 日:初始发布
© . All rights reserved.