Redirecting an OnKeyDown override

M

Minerva Jones

I override OnKeyDown in my form, and my form has KeyPreview=true. I'm
trying to implement it such that if the user starts typing, focus
jumps to a specific textbox without them having to select it. So in
OnKeyDown, I can say tbInput.Focus(), but the problem is that the
first key is missed (the one that OnKeyDown was called for). I figure
I could have some convoluted logic to add the character to
tbInput.Text, but the KeyDown might shift or a cursor key or any other
key that I'd want the textbox to receive but can't just add onto
..Text. I just feel I want to pass the OnKeyDown event onto the
textbox, but I don't see a way to do this.

Any ideas? Thanks!
 
G

Guest

The problem is that the current focused control is handling the event. You
need to intercept the OnKeyDown event, verify the focus control. If your
text box has focus then do nothing. If it is not your text box, then Set
focus on the control and then call the PInvoke method PostKeybdMessage or
call keybd_event twice, once with the KEYEVENTF_KEYUP not set and then again
with it set.

Rick D
Contractor
 
M

Minerva Jones

The problem is that the current focused control is handling the event. You
need to intercept the OnKeyDown event, verify the focus control. If your
text box has focus then do nothing. If it is not your text box, then Set
focus on the control and then call the PInvoke method PostKeybdMessage or
call keybd_event twice, once with the KEYEVENTF_KEYUP not set and then again
with it set.

I used the keybd_event technique and I'm pleased to say that it works
great, even with backspace and delete. My code is simply:

keyb_event ((byte)e.KeyValue, 0, 0, 0);
keyb_event ((byte)e.KeyValue, 0, KEYEVENTF_KEYUP, 0);

like you said. I wasn't sure whether I should try to swallow the
original keydown by setting e.Handled and/or not calling the base
class, but it works fine in either case.

Thanks again!
 

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