Reputation: 1917
I have created a class in VB.Net that is a child of DataGridView
. I am trying to create a method that detects when there has been a left click on one of the column headers, and then checks to see if the CTRL key is pressed when the click event fires. This is the code I have so far:
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
It's suppose to be simple right now, and just pop up a message box when holding either CTRL key and left clicking on one of the headers. However nothing is happened. I know the event method is firing, because if I move the MessageBox
line into an Else
block under the If
statement, I get the message boxes appearing. What am I doing wrong?
Upvotes: 2
Views: 1623
Reputation: 11773
You can probably adapt this to your needs
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
Upvotes: 1
Reputation: 112712
The condition should be
Control.ModifierKeys = Keys.LControlKey Or Control.ModifierKeys = Keys.RControlKey
because Keys.LControlKey Or Keys.RControlKey
combines the two Keys
values to form a new one containing both, LControlKey
and RControlKey
. This would mean that you have to press both control keys at the same time.
See: Use Enumerated Values with Bit Flags to Handle Multiple Options
Okay, it looks like you are getting a Keys.Control
, no matter which control key you are pressing. So simply test
if Control.ModifierKeys = Keys.Control Then
Upvotes: 0
Reputation: 7111
Control.ModifierKeys
is of type System.Windows.Forms.Keys
which is an enumerate type annotated with the FlagsAttribute
. You probably want to test a condition something like:
(Control.ModifierKeys AND Keys.LControlKey = Keys.LControlKey) OR (Control.ModifierKeys AND Keys.RControlKey = Keys.RControlKey)
The first half of that expression says "are all the bits of Keys.LControlKey
set in Control.ModifierKeys
. The second half does the same thing for Keys.RControlKey
.
Upvotes: 2