开发者

How can I check if a character is a valid Key in VB.NET?

开发者 https://www.devze.com 2023-01-08 06:31 出处:网络
I need to check if a character is a valid Key (type) in VB.NET (I n开发者_如何学Goeed to turn \"K\" into Keys.K, for example). I am currently doing this to convert it:

I need to check if a character is a valid Key (type) in VB.NET (I n开发者_如何学Goeed to turn "K" into Keys.K, for example). I am currently doing this to convert it:

Keys.Parse(GetType(Keys), key, False)

However, if key is not valid it throws an exception. How can I check if key is a valid character?


Enums do not have a TryParse method, therefore, you could do something like this:

Public Function IsValidKey(ByVal key As String) As Keys

    If Not [Enum].IsDefined(GetType(Keys), key) Then
        Return Keys.None
    End If

    Return CType(Keys.Parse(GetType(Keys), key, False), Keys)

End Function

Use it like this:

Dim k As Keys = IsValidKey("K")
If k <> Keys.None Then
  ' valid key
else
  ' invalid key
End If


You should use Keys.TryParse (Available in .Net 4.0). It will return true if key is a valid key, false otherwise (Doesn't throw).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号