Solved

Disabling BackSpace and Delete Keys

Posted on 1998-12-04
16
3,995 Views
Last Modified: 2008-02-01
I wanted to disable the BackSpace and Delete keys in a TextBox.  As a simple example I created a form with a single TextBox and added the following code:

Private Sub Text1_KeyDown(KeyCode As Integer, Shift As Integer)
  Select Case KeyCode
    Case vbKeyBack: KeyCode = 0
    Case vbKeyDelete: KeyCode = 0
  End Select
End Sub

It disables the Delete key but has no effect on the BackSpace key.

So then I ERASED the KeyDown code (above) and substituted the following code:

Private Sub Text1_KeyPress(KeyAscii As Integer)
  Select Case KeyAscii
    Case vbKeyBack: KeyAscii = 0
    Case vbKeyDelete: KeyAscii = 0
  End Select
End Sub

In this case it disables the BackSpace key but has no effect on the Delete key!

What gives!  When disabling keys, how do I know whether to put the code in KeyPress or KeyDown events?

dougr
0
Comment
Question by:dougr
  • 5
  • 3
  • 2
  • +4
16 Comments
 
LVL 7

Expert Comment

by:tward
Comment Utility
Try the following:

Private Sub Text1_KeyDown(KeyCode As Integer, Shift As Integer)
 
  If KeyCode = vbKeyDelete Then
   
    KeyCode = 0
 
  ElseIf KeyCode = vbKeyBack Then
       
        KeyCode = 0
       
  End If
 
End Sub

Private Sub Text1_KeyPress(KeyAscii As Integer)
 
  If KeyAscii = 8 Then
   
    KeyAscii = 0
   
  End If
 
End Sub



0
 

Author Comment

by:dougr
Comment Utility
To: tward

I appreciate you taking the time to respond to my question, however you are basically telling me what I already knew (see my code in the question).

Your statement "If KeyAscii = 8...." is essentially the same as my "If KeyAscii = vbKeyBack ....." because the value of the Key Code Constant for vbKeyBack = 8.

I was hoping for a more general and theoretical answer on my question: "How do I know whether to put the code in KeyPress or KeyDown events?"

My specific question was for the BackSpace and Delete keys, but there is obviously a subtle difference between the KeyPress and KeyDown events for certain keys, and it would appear that some keys fall into one category and some in the other.  I sort of wanted to know both the "why" and "how" of these differences.

dougr

0
 
LVL 7

Expert Comment

by:Inteqam
Comment Utility
why don't you simply use both events , one for the delete and the other for the backspace?

because i think , when you press the delete key the keydown event is called first , but if you press the back space the keypress event is called first .

hope this will work

0
 
LVL 3

Expert Comment

by:vikiing
Comment Utility
KeyPress event is activated when users press AND releases a key; while KeyDown works only when press occurs (system doesn't wait key to be released).

0
 
LVL 3

Expert Comment

by:vikiing
Comment Utility
KeyPress event is activated when users press AND releases a key; while KeyDown works only when press occurs (system doesn't wait key to be released).

0
 
LVL 7

Expert Comment

by:Inteqam
Comment Utility
OK , and because of that i think that the delete triggers the keydown event

0
 

Author Comment

by:dougr
Comment Utility
Thanks to Inteqam and vikiing for your answers and comments.  I am always amazed that I get these answers in the middle of the night here (i.e. 4-5 a.m.)!  But then I forget there are parts of the world where people are wide awake when I am asleep!  Computer programmers are a strange breed and some of us do in fact stay awake till 4-5 a.m.  But since today is MY BIRTHDAY (Dec 5) I went to bed a little earlier (3:00 a.m.) last night!

The answers I have received are all correct, but oversimplified in terms of what I was hoping for.  I guess I am not asking the question clearly enough.  Let me try once more before I award any points.

As I said in my previous comment, I already know HOW to disable the Delete and BackSpace keys and by trial and error I have learned how to disable and trap OTHER KEYS using combinations of KeyPress and KeyDown events.  In fact I have written many programs where I trap Insert, Delete, BackSpace, Tab, Escape, Enter, F1-F12 etc. The example I gave was intended to be only a SIMPLIFICATION to make the question easier to understand.

Vikiing's answers (both of them!) did give me some new information related to the differences between KeyDown and KeyPress.  And as I said in my comment, I was hoping for a more GENERAL and THEORETICAL answer on my question: "How do I know whether to put the code in KeyPress or KeyDown events?"

I really want to know more of the background theory as to why MicroSoft would choose to have some keys fall into one category (KeyDown) and some in the other (KeyPress).  I chose to discuss the Delete and BackSpace keys simply because they seem to highlight the point best.

Delete and BackSpace BOTH perform the function of deleting text.  "Delete" erases the character AT the cursor position and "BackSpace" erases the character to the LEFT of the cursor position.  It is BECAUSE OF THESE SIMILARITIES that I am puzzled why they are treated so differently.

I have doubled the points for what I originally thought might be an easy question, and I would appreciate receiving an answer that is:

1. More than a simple "just try this" answer designed to solve the simplified question I originally posed.

2. More theoretical, describing the REASONING behind the MicroSoft choice to put different keys in the KeyPress or KeyDown events.

3. A discussion of WHICH KEYS fall into which category.

I did not intend to be mean or nasty in rejecting the answers given so far.  The fault is probably mine for not asking the question clearly enough.  I hope this comment clarifies it.  Please READ MY QUESTION AND ALL COMMENTS carefully before answering.

dougr
0
 
LVL 1

Expert Comment

by:muffinthedog
Comment Utility
Roundabout but werkz fer me!
Forgive format

Hook the text box like...

    gHW = Text1.hwnd
    Hook

Be sure to Unhook the thingee like

    Unhook

Use something like

Option Explicit

Declare Function CallWindowProc Lib "user32" Alias _
"CallWindowProcA" (ByVal lpPrevWndFunc As Long, _
    ByVal hwnd As Long, ByVal Msg As Long, _
    ByVal wParam As Long, ByVal lParam As Long) As Long

Declare Function SetWindowLong Lib "user32" Alias _
"SetWindowLongA" (ByVal hwnd As Long, _
ByVal nIndex As Long, ByVal dwNewLong As Long) As Long

'Hook messages
Public Const WM_KEYDOWN = &H100
Public Const WM_KEYUP = &H101
Public Const WM_CHAR = &H102

'SetWindowLong message to subclass window
Public Const GWL_WNDPROC = -4

Global lpPrevWndProc As Long
Global gHW As Long
   
Public Sub Hook()
    lpPrevWndProc = SetWindowLong(gHW, GWL_WNDPROC, _
    AddressOf WindowProc)
End Sub

Public Sub Unhook()
    Dim temp As Long
    temp = SetWindowLong(gHW, GWL_WNDPROC, _
    lpPrevWndProc)
End Sub

Function WindowProc(ByVal hw As Long, ByVal uMsg As _
Long, ByVal wParam As Long, ByVal lParam As Long) As _
Long
    Select Case uMsg
    Case WM_KEYDOWN, WM_KEYUP
        If wParam = vbKeyDelete Or wParam = vbKeyBack Then Exit Function
    Case WM_CHAR
        If wParam = vbKeyBack Then Exit Function
    End Select
    WindowProc = CallWindowProc(lpPrevWndProc, hw, _
        uMsg, wParam, lParam)
End Function
   



0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 

Author Comment

by:dougr
Comment Utility
To: muffinthedog

I am sorry, but this answer makes no sense to me, especially in view of my somewhat verbose, but detailed last comment.  Did you answer someone else's question by mistake?

I appreciate that you may have spent some time on it, but I don't understand your "hooks" and "thingees" and how it relates to my wanting to know some background info on the KeyPress and KeyDown events.  Am I stupid or does anyone else understand this answer?

Doug
0
 
LVL 1

Expert Comment

by:muffinthedog
Comment Utility
Just a note after reading your last comment...

VB sucks... lets face it...

As for MS's methodology... you got me!

Windows is just a multitude of messages broadcast to a multide of objects which either act on the message or send it along its merry path.

A keypress is a keypress is a keypress... how the keypress is interpreted and acted upon by the window with the keyboard focus is determined by the program. Why MS used a "Thunder TextBox" rather than an edit control is a matter of speculation and frustration.

I included my example to show how you could process any messages sent to the control in a single function.
0
 
LVL 3

Expert Comment

by:vbWhiz
Comment Utility
This question is unlike most others I have seen.

Why?

Because you ask why and not how.

Why ask how?

You ask how because you want to know how to achieve a certain result.

Why ask why?

You ask why because you want to know the theory behind the result, the reason for the quirky behavior.

Why? Why?

Why I cannot tell, how I can usually tell.

Why, you must search within yourself for the answer.
0
 
LVL 3

Expert Comment

by:vikiing
Comment Utility
>I am always amazed that I get these answers in the middle of
>the night here (i.e. 4-5 a.m.)!  But then I forget there are
>parts of the world where people are wide awake when I am
>asleep!

That's a big truth. Many times occurs that while you sleep, we other are working for you... :) :)


>Computer programmers are a strange breed and

That's another big, enormous truth...  ;)

0
 
LVL 1

Accepted Solution

by:
Jason_Row earned 80 total points
Comment Utility
Well I hope some of this info will help to clear up the question on when to use keyPress versus keyDown.

The KeyPress event detects when an alphanumeric key was pressed.  Unlike the KeyDown and KeyUp events, KeyPress doesn't detect the following:  arrow keys, special combinations of SHIFT, CTRL, and ALT keys, and function keys that are not attached to menu commands.

At least this is the information that MS wishes to use on the certification exams. They say that if you wish to check whether or not an alphanumeric character (0-9,a,A,b,B, etc) has been inputed then you would use keyPress. If you're looking for function keys, arrow keys, etc... then use the keyUp or keyDown events.

I hope this helps.

Jason Row


0
 

Author Comment

by:dougr
Comment Utility
To: vbWhiz

Thank you for your somewhat philosophical discourse on the difference between "WHY" and "HOW".  I am not sure how it helps answer my query, but since you posed the question I will try to answer it.

To me, anyone in the problem solving business, whether scientist, social worker or programmer always wants to know the "WHY" as well as the "HOW".  "HOW" can lead you to an immediate, pragmatic solution to a problem without ever understanding the "WHY".  "WHY" can lead you to an understanding of the theory behind the problem and the conditions which caused it.

The final benefits of full understanding can lead you to solving or even preventing similar and related problems.  Thus you add to your problem solving skills a tool which carries you far beyond a simple solution to a specific immediate problem.

If Einstein had not asked "WHY" instead of just "HOW" we would never have had the Theory of Relativity and would still be working with Newton's theories (which are still accurate for 99.9% of our problems, but give an incomplete undestanding of the more complex problems).

dougr
0
 
LVL 3

Expert Comment

by:vbWhiz
Comment Utility
I completely agree that understanding the 'Why' gives a greater ability to anticipate problems and/or design a better app. I am always striving to have a better understanding of how Windows works (or doesn't in some cases) and build my own theories on why. I guess my point was (If I had one - I was in kind of a weird philisophical mood) that you had rejected some pretty good answers - especially muffinthedog's which gave a complete view of how windows communicates messages to the textbox. You seemed to want to know why VB behaves the way it does, and I guess I can tell you how VB behaves and what Windows is telling the textbox behind the scenes. But as to why the VB designers chose to have the keydown, keyup, and keypress events behave the way they do? I guess I can't answer that question - I can make my own theory but they are the ones who decided to make VB work the way it does.
0
 

Author Comment

by:dougr
Comment Utility
To: vbWhiz
 
I appreciate your last comment.  Perhaps from what you say, I owe muffinthedog an apology for rejecting his answer (sorry muffinthedog!).  I didn't understand what he was driving at, but that was probably more the problem with my lack of experience and understanding than it was with his answer.

Learning VB has been an experience.  It is bad enough when I trip on my own mistakes, but it is really frustrating when you discover (once in a while) that the bug you spent hours or days tracking down is a MicroSoft VB bug over which you have no control.

Thanks again for your indulgence and help.

dougr
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

You can of course define an array to hold data that is of a particular type like an array of Strings to hold customer names or an array of Doubles to hold customer sales, but what do you do if you want to coordinate that data? This article describes…
Since upgrading to Office 2013 or higher installing the Smart Indenter addin will fail. This article will explain how to install it so it will work regardless of the Office version installed.
As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
Get people started with the process of using Access VBA to control Outlook using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Microsoft Outlook. Using automation, an Access applic…

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now