Link to home
Start Free TrialLog in
Avatar of Craig_Sparks
Craig_Sparks

asked on

How to handle all KeyPress events in a form?

I know how to create an event handler for keypress events only when they are with respect to an object in the form itself, like a button or a textbox, etc.

How would I create one for the form itself and disable ALL the default handlers, like tab, return, arrow keys etc?

I've tried adding the handler for:

AddHandler Form1.KeyPress
AddHandler Me.KeyPress
AddHandler MyBase.KeyPress

all without sucess, which just shows how lost I am on this topic and would appreciate any help anyone has to offer. Thanks.

Craig

ASKER CERTIFIED SOLUTION
Avatar of gafoorgk
gafoorgk

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Craig_Sparks
Craig_Sparks

ASKER

Sorry I didnt post that. VB.NET 2002

The same KeyPreview for a form exists in VB.NET 2002 check that.
I'm still not getting how to fix it.

I have a single form in the program, Form1

In the load section I put:

Private Sub Form1_Load(ByVal sender ...
Me.KeyPreview = True
...
End Sub

Then try:

Private Sub Form1_KeyPress(ByVal sender As System.Object, ByVal e As KeyPressEventArgs) Handles MyBase.KeyPress

        Label1.Text = e.KeyChar
        e.Handled = True

    End Sub

But it doesn't catch any of the key presses. They system still does, tabs around the buttons in the form etc. The MyBase part has to be wrong on my part, there is no option for Form1.KeyPress only options for the various buttons and MyBase, thats it.  If I replace MyBase with say TextBox1 it works great. How can I achieve this same functionality for the entire form?

Is there a way to effectivly pull off: Handles Form1.KeyPress?

Thanks,

Craig





Try the following:

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.KeyPreview = True
    End Sub


    Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress
        Label1.Text = e.KeyChar
        e.Handled = True
    End Sub
mybad. Please ignore my previous post..
Did you try keyDown?
Yes I have tried KeyDown and KeyPress with the same results.  Even with the KeyPreview = True something is intercepting default key moves, like arrows, tabs, space etc. But when something like a text box has focus in the form then the MyBase does catch the key presses.

Any thoughts?

Actually the MyBase catches all the KeyDown events save for the special keys that I need actually. I dont need to focus any buttons etc and i can catch what keys are being pressed save for:

Arrow Keys, Tabs, Space, Enter and some others I'm sure ive missed.

How to catch those too?