C# - Changing parameters of an existing event handler
So, here's the deal. What I wanna do must be really simple, but I just can't find a solution that doesn't involve building a few classes and it wouldn't even be worth my trouble.
In a regular TextBox there is the OnKeyUp event. It's handler signature demands the sending object (of course) and a KeyEventArgs object. All I want is replace this KeyEventArgs with a CancelEventArgs object. Or, not even that, let's say that I just wanna add a new CancelEventArgs parameter to the handler. In other words, all I want is that if the wrong key is pressed, the whole event is cancelled.
I see there's a topic with a seemingly similar question, but开发者_StackOverflow中文版 that won't do. Any pointers?
Set the SuppressKeyPress property of the KeyEventArgs object of the KeyDown event to true to prevent user input.
No, you can't add an extra parameter to an existing event handler. After all, the TextBox
is going to raise that event - how would it know what to do for your extra parameter, or even your different one? It's been told that it will be given a KeyEventHandler
to call, so it believes it can call that event handler with the normal arguments.
How would you expect this to work from the point of view of the TextBox
?
As SemVanmeenen suggests, you may well find that SuppressKeyPress
is what you want, although that's not quite the same as "cancelling" the whole event. It's worth making sure you understand why you can't change event handler parameters though.
If the above doesn't help, you might want to read my article on events and delegates for a better feel for how they work.
精彩评论