【问题标题】:Implement a right-click for an entire group of check boxes?为整组复选框实现右键单击?
【发布时间】:2016-04-19 22:30:01
【问题描述】:

我在GroupBox 中有一系列CheckBox(es),用于选择用户想要运行的报告。它们通常都是Checked,这是最常见的情况,但只想运行一个也很常见。我认为右键单击一个框将其打开并关闭所有其他框会很有用。

在复选框上实现MouseClick 事件很容易,但问题是它们有很多,并且列表不断被添加。所以第一个问题:有没有办法让单个 MouseClick 处理程序适用于任何复选框,甚至是我们还没有的复选框?

另一种选择似乎是使用GroupBox.Controls 集合循环检查复选框并查看单击了哪个复选框,然后根据需要为所有复选框设置Checked。然而,CheckBox always 似乎拦截了MouseClick 事件,即使AutoCheck 已关闭。所以我的第二个问题:有没有办法关闭复选框中的点击处理,以便群组处理事件?

如果有其他方法可以解决这个问题,请告诉我!

【问题讨论】:

  • 使用一个通用的事件处理程序来处理它们。添加新的时,将其连接到同一个处理程序
  • 好的,没有我想要的那么自动化,但它可以工作。但现在我很困惑如何解释鼠标位置。 e(vent).location 返回相对于 that 控件的值,因此您会得到像 32,24 这样的小数字。这在每个控件的范围内,因此我需要将坐标转换,但我不确定如何将其转换为通用参考框架。
  • 至于您的第二个问题,尝试使用 mousedown 事件,您可以在其中检查以确保正在使用右键,将发件人分配给复选框类型的变量,通过复选框设置创建循环将它们设置为 false 并将保存发件人的变量设置为 true。
  • 自动化程度较低是什么意思?这可以通过 AddHandler 并在运行时循环并添加您的控件来完成。
  • 为什么需要定位?我认为这与检查点击有关?

标签: .net vb.net checkbox


【解决方案1】:

这是我在我的 cmets 中谈论的一个例子。将 FlowLayoutPanel 添加到表单(保留它 flowlayoutpanel1)

'This is done to show automatic generation of a list of reports.
'You might get this from a folder of reports, or a database or similar store
'By adding and taking away from this list you will notice that the code still functions the same.
'Just remember, you would dynamically fill the reports list in your real-world application.
Dim Reports As New List(Of String) From {"Report1", "Report2", "Report3", "Report4", "Report5", "Report6", "Report7", "Report8"}

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    'I'm using a flowlayoutpanel so that the controls are added
    'without having to worry about placement
    FlowLayoutPanel1.AutoScroll = True
    'Here is where we loop through the list of reports and add them to the 
    'flowlayoutpanel and give them a common handler
    For Each rpt As String In Reports
        Dim chkRpt As New CheckBox
        chkRpt.Text = rpt
        chkRpt.Height = 17
        chkRpt.Checked = True
        AddHandler chkRpt.MouseDown, AddressOf CustomMouseDown
        FlowLayoutPanel1.Controls.Add(chkRpt)
    Next
End Sub

'Here is the code to allow a right click to select the current checkbox
'and remove all other checked items.
Private Sub CustomMouseDown(sender As Object, e As MouseEventArgs)
    If e.Button = Windows.Forms.MouseButtons.Right Then
        Dim curChk As CheckBox = CType(sender, CheckBox)
        For Each chk As CheckBox In FlowLayoutPanel1.Controls.OfType(Of CheckBox)()
            chk.Checked = False
        Next
        curChk.Checked = True
    End If
End Sub

【讨论】:

  • 非常好,确实可以处理新的复选框!
猜你喜欢
  • 1970-01-01
  • 2012-11-06
  • 1970-01-01
  • 1970-01-01
  • 2010-12-01
  • 2013-08-22
  • 2010-11-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多