.NET Core's KeyboardEventArgs
class contains the Key
and Code
properties, which are both strings. So I must use magic strings like if (e.Key == "Backspace") { }
.
.NET Framework (and the current Desktop API) have the System.Windows.Forms.Keys
enum, which allows us to write code without magic strings, e.g. if (e.Key == Keys.Back) { }
.
Is there an equivalent enum for .NET Core? I want this for a Blazor app.
CodePudding user response:
The KeyboardEventArgs
you're referring to is Blazor's own Microsoft.AspNetCore.Components.Web.KeyboardEventArgs
which is the Blazor view of the DOM's KeyboardEvent
.
While the DOM's KeyboardEvent
does have integer (number
in JS)-typed members, these are all either obsolete, non-standard or only ever seen in draft specs, and/or have values that vary between browsers and/or OS families, which makes them non-portable and so it's no surprise that Blazor doesn't use them.
Of the myriad proprietary and draft members of KeyboardEvent
DOM interface, only code
and key
are still defined in the current draft DOM UI Events specification and draft DOM Level 3 Events specification, all other key/char-indicator members are obsolete. I've made this table to list those members:
KeyboardEvent property |
Type | Printable | Nonprintable | Status | Notes |
---|---|---|---|---|---|
char |
string |
True | False | Obsolete | |
charCode |
number |
True | False | Obsolete | Only used in keypress event (not keydown , etc). Returns ambiguous results in many cases. |
code |
string |
True | True | Current | |
key |
string |
True | True | Current | |
keyIdentifier |
string |
True | True | Obsolete | Proprietary to Apple Safari/WebKit. |
keyCode |
number |
False | True | Obsolete | |
which |
number |
True | True | Obsolete | Inherited from UIEvent . Aliases charCode for printable chars, or keyCode for nonprintable chars. |
Consider that C#'s enum
-types are all integer-based: as of C# 11 in 2022 there is no concept of a String
-based enum
type which, which means if you (or the Blazor dev team) did want an enum
-based member of Blazor's KeyboardEventArgs
then you (or they) would have to manually maintain a mapping between KeyboardEvent.code/key
string values and their enum members, which would be a huge PITA to maintain, especially given that as of October 2022 the DOM UI Events spec is still in the draft stage.