KeyPress/KeyDown difficulties

C

Craig Buchanan

i am trying to capture the ctrl-d key combination in the form's
KeyPress/KeyDown events. The KeyAscii value of the KeyPress is 4, when i
would expect 100 ('d') or 68 ('D'). See code below.

Also, is there a 'best practice' for testing keycode combinations (someone
other than a large number of IF THEN ELSE statements)? I'm doing If
KeyAscii = vbKeyD And m_CtrlPressed Then

Can someone share his/her insight?

Thanks,

Craig

<code>
Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)

' Use bit masks to determine which key was pressed.
m_ShiftPressed = (Shift And acShiftMask) > 0
m_AltPressed = (Shift And acAltMask) > 0
m_CtrlPressed = (Shift And acCtrlMask) > 0

End Sub

Private Sub Form_KeyPress(KeyAscii As Integer)

' Convert ANSI value to character string.
Dim strCharacter As String: strCharacter = Chr(KeyAscii)

' Convert character to upper case, then to ANSI value.
KeyAscii = Asc(UCase(strCharacter))

If KeyAscii = vbKeyD And m_CtrlPressed Then
MsgBox "delete me"
End If

End Sub
</code>
 
C

Chaim

From my UNIX days, I know that the Control key is a modifier. CTRL-A, for
example, is 0x01, CTRL-B is 0x02, etc. So, D, being the 4th letter of the
alphabet, will generate 0x04 as a control character.

How does the KeyPress procedure know the value of m_(Shift|Ctrl|Alt)Pressed?
Are these global to your module?

Do you have the KeyPreview property for the form set to Yes? The form won't
receive the key strokes unless: 1) there are no controls or all visible
controls are disabled; or 2) KeyPreview for the form is set to Yes.

As far as style, you could try a 'select case' statement. It saves some
typing and is more easily extensible than 'if ... elseif ... else ... end if'
statements.

Good Luck!
 
B

Brendan Reynolds

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)

If KeyCode = vbKeyD And ((Shift And acCtrlMask) <> 0) Then
MsgBox "Ctrl+D pressed."
End If

End Sub

Re the second part of the question, if you have a large number of key
presses you want to test for, especially if you want to use them throughout
your application (not just one form), you might want to consider using an
AutoKeys macro ...

http://office.microsoft.com/assistance/hfws.aspx?AssetID=HP051866491033
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top