Annoying little issue... Disconnecting Form level event and Control level event...

  • Thread starter Thread starter HyperX
  • Start date Start date
H

HyperX

Form1_Keypress(sender, KeyPress e) is a Form level event.

On TextBox key press, Form1_KeyPress() gets called. When I press a
key in TextBox, we assume, the sender has to be TextBox, right? No!
I do

sender.GetType() = Form1!!

Thats what is annoying...

How can I know from the Form1_KeyPress(x, x) if the user pressed a key
from within a control??

I hope I made it clear.

Thanks,

HyperX.
 
HyperX,

I would try calling the GetActiveWindow API function through the
P/Invoke layer, getting the window handle of the currently active window.
Once you have that, I would call the static FromHandle method on the Control
class, and see what it returns. You can then check the type of the returned
value (assuming there is one) to see what currently has the focus.

Hope this helps.
 
HyperX said:
Form1_KeyPress() gets called. When I press a
key in TextBox, we assume, the sender has to be
TextBox, right?

No. You would expect the sender to be the object sending you the event. The
event in this case is Form_KeyPress, not TextBox_KeyPress.
How can I know from the Form1_KeyPress(x, x)
if the user pressed a key from within a control??

if (MyTextBox.Focused)

P.
 
Hi HyperX,
Do you mean that you handle the form's KeyPress event and you have form's
KeyPreview set to *true*.
If this is the case: yes, indeed the form is the sender of the event. The
form sends this event and *sender* has to be the form. The key EditBox
hasn't process the key yet. If you need to know the control to which this
key message is addressed check form's ActiveControl property. This property
keeps the focused control and this is the only control that could be the
final destination for the key messages the form has intercepted.
 
I forgot to mention is that I have about 800 controls spread through 10
tabs...

Nicholas,

Sorry to bother you as you might answer to 10 more people by the time
you spend on this... but, do you have any sample code to go by?

Thanks,

HyperX.
 
Back
Top