代码之家  ›  专栏  ›  技术社区  ›  Skitzafreak

检测在左键单击DataGridView标题时是否按了Ctrl键

  •  1
  • Skitzafreak  · 技术社区  · 6 年前

    我在vb.net中创建了一个类,它是 DataGridView . 我正在尝试创建一个方法,该方法检测在某个列标题上单击鼠标左键的时间,然后检查在单击事件激发时是否按了ctrl键。这是迄今为止我掌握的代码:

    Private Sub Self_ColumnHeaderLeftClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles Me.ColumnHeaderMouseClick
        If e.Button <> MouseButtons.Left Then Return
        If (Control.ModifierKeys = (Keys.LControlKey Or Keys.RControlKey) Then
            MessageBox.Show(Columns(e.ColumnIndex).Name)
        EndIf
    End Sub
    

    现在应该很简单,只要按住ctrl键并左键单击其中一个标题,就会弹出一个消息框。但是什么都没有发生。我知道事件方法正在触发,因为如果我移动 MessageBox 直线进入 Else 下块 If 语句,我得到消息框出现。我做错什么了?

    3 回复  |  直到 6 年前
        1
  •  2
  •   Flydog57    6 年前

    Control.ModifierKeys 属于类型 System.Windows.Forms.Keys 它是用 FlagsAttribute .你可能想测试一个条件,比如:

    (Control.ModifierKeys AND Keys.LControlKey = Keys.LControlKey) OR (Control.ModifierKeys AND Keys.RControlKey = Keys.RControlKey)
    

    这个表达式的前半部分说“都是 Keys.LControlKey 设置在 控件.修改键 . 下半场也做同样的事情 Keys.RControlKey .

        2
  •  0
  •   Olivier Jacot-Descombes    6 年前

    条件应该是

    Control.ModifierKeys = Keys.LControlKey Or Control.ModifierKeys = Keys.RControlKey
    

    因为 Keys.LControlKey Or Keys.RControlKey 两者结合 Keys 值以形成一个新的值,其中包含两个值, LControlKey RControlKey . 这意味着你必须同时按下两个控制键。

    见: Use Enumerated Values with Bit Flags to Handle Multiple Options


    好吧,看起来你得到了 Keys.Control ,无论您按哪个控制键。简单测试

    if Control.ModifierKeys = Keys.Control Then
    
        3
  •  0
  •   dbasnett    6 年前

    你也许可以根据你的需要来调整这个

    Private Sub SomeDGV_ColumnHeaderMouseClick(sender As Object,
                                                  e As DataGridViewCellMouseEventArgs) Handles dgvPending.ColumnHeaderMouseClick
    
        If e.Button = Windows.Forms.MouseButtons.Left Then
    
            If My.Computer.Keyboard.CtrlKeyDown Then
                'control key down
            Else
                '
            End If
    
        End If
    End Sub