I have this code:
if (PsionTeklogix.Keyboard.Keyboard.GetModifierKeyState(Key.Orange) == KeyState.Lock)
PsionTeklogix.Keyboard.Keyboard.InjectKeyboardCommand(Function.Orange, 0, 0);
if (PsionTeklogix.Keyboard.Keyboard.GetModifierKeyState(Key.Blue) == KeyState.Lock)
PsionTeklogix.Keyboard.Keyboard.InjectKeyboardCommand(Function.Blue, 0, 0);
if (PsionTeklogix.Keyboard.Keyboard.GetModifierKeyState(Key.Shift) == KeyState.Lock)
PsionTeklogix.Keyboard.Keyboard.InjectKeyboardCommand(Function.Shift, 0, 0);
if (PsionTeklogix.Keyboard.Keyboard.GetModifierKeyState(Key.Control) == KeyState.Lock)
PsionTeklogix.Keyboard.Keyboard.InjectKeyboardCommand(Function.Control, 0, 0);
...
and I want to refactor the code separating the key / function definition from the actions. Key.xxx and Function.xxx aren't from the same type.
eg: in Python, I could simply do something like:
keys = (
( Key.Orange, Function.Orange ),
( Key.Blue , Function.Blue ),
( Key.Shift , Function.Shift ),
...
)
psi_key = PsionTeklogix.Keyboard.Keyboard
for key, func in keys:
if psi_key.GetModifierKeyState(key) == KeyState.Lock):
psi_key.InjectKeyboardCommand(func, 0, 0)
What's "the right way" to do in C#?
You can do something very similar:
Dictionary<Key, Function> keys = new Dictionary<Key, Function>
{
{ Key.Orange, Function.Orange },
{ Key.Blue, Function.Blue }
...
};
foreach (var pair in keys)
{
if (Keyboard.GetModifierKeyState(pair.Key) == KeyState.Locked)
{
Keyboard.InjectKeyboardCommand(pair.Value, 0, 0);
}
}
You could even use LINQ if you wanted to:
foreach (var pair in keys.Where(pair =>
Keyboard.GetModifierKeyState(pair.Key) == KeyState.Locked)
{
Keyboard.InjectKeyboardCommand(pair.Value, 0, 0);
}
Now using a Dictionary
is somewhat odd here given that we're not looking anything up. If you're using .NET 4 you could use a list of tuples instead:
var keys = new List<Tuple<Key, Function>>()
{
Tuple.Of(Key.Orange, Function.Orange),
Tuple.Of(Key.Blue, Function.Blue),
...
};
and adjust the loop accordingly. You could use an anonymous type, too:
var keys = new[]
{
new { Key = Key.Orange, Function = Function.Orange },
new { Key = Key.Blue, Function = Function.Blue },
...
};
They're all basically acting as ways of representing key/function pairs :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With