Hi all , I am receiving a casting error message when I try to perform the following code...
private void txtSnagDetailsActionBy_GotFocus(object sender, System.EventArgs e)
{
KeyEventArgs ke = (KeyEventArgs)e;
}
Is this type of casting not possible
Tryst

Casting EventArgs object to KeyEventArgs - is it possible?
rfb
just tested it, and the pen doesn't create a MouseDown event :(
It seems strange that there isn't a dedicated event for pens in the CF1.0 Framework.
Tryst
Ashish Nayyar
what Cleo described was a safe way to cast to KeyEventArgs IF 'e' was of type KeyEventArgs but since it isn't, it can't be cast.
I think a Pen behaves like a mouse so, check the MouseDown event.
ry383
Thanks
Tryst
jacopo
Hi Tryst,
How does your project go Have you resolved your problem
Looking forward to your further improvement.
Regards,
Cleo
carlosalvidrez
Hi Tryst,
Thanks for contacting Microsoft!
The casting from parent class to child class can make sense if the instance of parent class is also that of the child class. Since it's a runtime-determined issue, the code you provide can be sucessfully compiled while running, if your dynamically-binding class is another child of the parent classs, the similar runtime error "Unable to cast object of type 'System.Windows.Forms.MouseEventArgs' to type 'System.Windows.Forms.KeyEventArgs'" will occur. So it's highly suggested adding a "if-condition" statement before it. For example:
private void txtSnagDetailsActionBy_GotFocus(object sender, System.EventArgs e)
{
if (e.GetType() == typeof(KeyEventArgs))
KeyEventArgs ke = (KeyEventArgs)e;
}
We sincerely hope this can be of help. If anything is unclear, please don't hesitate to get in touch. Any comments and further feedback from you will be welcome and highly valued.
Cheers,
Cleo
Warren13
you can't cast it like that because KeyEventArgs derives from EventArgs and since e is not a KeyEventArgs, it says that it can't cast it.
If e was of type KeyEventArgs then you could cast it to EventArgs.
Joe Rohde
A better way to cast, would actually be the following (that way you are not excluding classes that derive from KeyEventArgs):
KeyEventArgs ke = e as KeyEventArgs;
if (ke != null)
{
}
However, in saying that, in Cleo's example above and my example, the if statements are clearly never going evaluate to true. This is because the GotFocus event does not provide KeyEventArgs. If you are looking for key related properties such as if the control key is being pressed, have a look at Control.ModifierKeys property.
ShaunS
This doesn't work unfortunately. If I add a Watch on 'e' then it tells me its type is System.EventArgs, and not KeyEventArgs.
What I am trying to do is to find the event that is caused by the Pen when I select a control. I am told that its the same as the Enter key being pressed, but that is not true as my KeyDown events are not trapping when I select a control with the pen.
Tryst