Created
August 5, 2012 16:01
-
-
Save pragmatrix/3265540 to your computer and use it in GitHub Desktop.
(unfinished) Helper to convert WinRT Virtual Keys to ASCII
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Diagnostics; | |
using Windows.System; | |
namespace Toolbox.WinRT | |
{ | |
enum VKeyClass | |
{ | |
Control, // 0-31, 33-47, 91-95, 144-165 | |
Character, // 32, 48-90 | |
NumPad, // 96-111 | |
Function // 112 - 135 | |
} | |
public enum VKeyCharacterClass | |
{ | |
Space, | |
Numeric, | |
Alphabetic | |
} | |
static class VirtualKeyHelper | |
{ | |
public static char? tryConvertKeyToCharacter(VirtualKey key, ModifierKeys modifiers) | |
{ | |
if (modifiers != ModifierKeys.Shift && modifiers != ModifierKeys.None) | |
return null; | |
var classification = tryClassify(key); | |
if (classification == null || classification.Value != VKeyClass.Character) | |
return null; | |
var k = (int)key; | |
// don't handle the numeric key pad right now. | |
if (k >= 96) | |
return null; | |
bool shift = modifiers == ModifierKeys.Shift; | |
var charClass = tryClassifyCharacterKey(key); | |
if (charClass == null) | |
return null; | |
switch (charClass.Value) | |
{ | |
case VKeyCharacterClass.Alphabetic: | |
return (char)(shift ? k : k + ('a' - 'A')); | |
case VKeyCharacterClass.Space: | |
case VKeyCharacterClass.Numeric: | |
return (char)k; | |
} | |
return null; | |
} | |
public static VKeyClass? tryClassify(VirtualKey key) | |
{ | |
var k = (int)key; | |
if (k >= 112 && k <= 135) | |
return VKeyClass.Function; | |
if (k == 32 || k >= 48 && k <= 57 || k >= 65 && k <= 90) | |
return VKeyClass.Character; | |
if (k >= 96 && k <= 111) | |
return VKeyClass.NumPad; | |
if (k >= 0 && k <= 31 || k >= 33 && k <= 47 || k >= 91 && k <= 95 || k >= 144 && k <= 165) | |
return VKeyClass.Control; | |
return null; | |
} | |
public static VKeyCharacterClass? tryClassifyCharacterKey(VirtualKey key) | |
{ | |
Debug.Assert(tryClassify(key) == VKeyClass.Character); | |
var k = (int)key; | |
if (k == 32) | |
return VKeyCharacterClass.Space; | |
if (k >= 48 && k <= 57) | |
return VKeyCharacterClass.Numeric; | |
if (k >= 65 && k <= 90) | |
return VKeyCharacterClass.Alphabetic; | |
return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment