Recognizing sender in form event...

  • Thread starter Thread starter Hyper X
  • Start date Start date
H

Hyper X

Hi,

How do I cancel the event out if the sender is a textbox, combobox,
checkbox etc in form level event like Form1_KeyPress??

private void Form1_KeyPress(object sender, KeyEventArgs e)
{
///
/// Figure out if the event is from Form1... and NOT from the
textbox...
/// Cancel the event out if the sender is anyone other than form or
tab.
///
}

I tried sender.GetType() and it always comes up as
"MyNamespace.WinUI.Form1" even though I pressed the key from the
TextBox.

How can I know if the sender is a textbox from the Form1_KeyPress??

Since textbox is on the form, form level event gets executed, which is
fine (or may not be fine?? since this should be handled in
TextBox_KeyPress event.)

Any help from any one is greatly appreciated.

Thanks,

HyperX.


-------> The next statement is true. The previous statement is false.
<--------
 
Are you catching the Form KeyPress event or the TextBox KeyPress event

I have a Form with a button and a textbox. Both the button and keypress have the KeyPress event sent to the same handler. You can check to see if the sender of an event is a textbox, button exc using 'is' as shown below (but my sender.GetType( ) works fine too)

private void Form1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e

MessageBox.Show( sender.GetType( ).ToString( ) )

if ( sender is Button

MessageBox.Show( "Button" )

if ( sender is TextBox

MessageBox.Show( "TextBox" )



If that doesn't work, you will have to post more code so we can see exactly what is going o

HT

RS
 
Thats the exact code that I tried that code before I posted the message.

The sender in Form1_Keypress event is always Form1, no matter if the
event is coming from TextBox, ComboBox, checkbox etc.

I already have about 800 controls spread through 10 tabs. I don't want
to try hooking up all controls to an event and cancel the event... (I
don't think thats a good idea)

There should be some way that I can recognize if the event is from the
child TextBox, or the parent form FROM the Form1_KeyPress...

All these little things annoy to be a CSharper...
 
okay, here is the code...


protected override void ProcessFormKeyDownCustom(object sender,
System.Windows.Forms.KeyEventArgs e)
{
Type objType = sender.GetType();
if (objType == typeof(TextBox) || objType == typeof(ComboBox) ||
objType == typeof(CheckBox) || objType == typeof(Button) ||
objType == typeof(Label) || objType == typeof(UltraGrid))
{
e.Handled = true;
return;
}
else
{
//do form related stuff...
}

}

The problem is, objType is always Form1() even though the event that
caused this to fire up is a TextBox...
 
Back
Top