· 01:18
Welcome to CodeSOD! Today, we're diving into a classic case of using the wrong kind of character in C#. Our story comes from Austin, who stumbled upon some quirky code in an older Windows Forms application. At first glance, it seems like simple literals replacing constants, but there’s more to it.
Here’s what he found: the code checks for specific key presses using the KeyPressEvent, which is intended for typing. Instead of using the expected KeyDown event, where you’d typically check for combinations like CTRL+D with e.KeyCode
, our developer opted for e.KeyChar
. This resulted in some unexpected behavior.
For instance, CTRL+D corresponds to the "end of transmit" character, and CTRL+G is the bell character. But when it comes to keys like Home and End? Well, those don't have ASCII character codes. Instead, they were turned into characters that didn’t even remotely represent their intended functions, with Home becoming "$" and End turning into "#".
Austin’s fix was simple but effective: he moved to the correct event type and switched to using KeyCodes. This not only rectified the issue but also made the code more readable.
Remember, even small choices in coding can lead to unexpected consequences. That’s it for today! Keep coding smart!
Link to Article
Listen to jawbreaker.io using one of many popular podcasting apps or directories.