Alexander
Alexander

Reputation: 4219

Converting a List of Enums into Flags in C#

I'm currently using a hotkey package that takes a set of Key and ModifierKey enumerations as flags.

As an example, this would register the Ctrl+Shift+4 hotkey:

hotKey = new GlobalHotKey.HotKey(Key.D4, ModifierKeys.Shift | ModifierKeys.Control);

From my understanding, when passing in an enumeration as a flag, it's actually just performing a bitwise or operation (hence the syntax).

For my UI, I need to store keypresses in a List<Key>. However, I eventually need to set the pressed keys as a new hotkey, and I need to convert my List<Key> to a plain old Key (with the flags operation).

Because I thought it was just a bitwise or operation, I attempted this solution with LINQ.

hotkeysPressedBitwise = hotkeysPressed.Select(f => f).Aggregate((x, y) => x | y);

where hotkeysPressed is my List<Key>. My LINQ statement works correctly, however, it is not giving me the desired effect when actually passing it into my function.

For instance, when I pass in X and C, my LINQ statement returns a value equal to X | C. If I cast that to the Key enum, it gives me the F22 key for some reason.

hotKey = new GlobalHotKey.HotKey( keys , ModifierKeys.None); doesn't work. (I set ModifierKeys to none for now out of similicity).

Am I missing something here?

Upvotes: 1

Views: 399

Answers (2)

Bradley Moorfield
Bradley Moorfield

Reputation: 867

Hotkeys aren't usually designed to allow multiple regular keys (such as the letters X and C) in a combination, in contrast to modifier keys (such as control, shift, alt) which can be combined.

Because of this, Key enumerations won't usually work in a predictable way when using bitwise operations on regular keys, as they will be assigned sequential values, whereas modifier keys will have values that are powers-of-two

Upvotes: 1

thepirat000
thepirat000

Reputation: 13089

Assuming you're referring to System.Windows.Forms.Keys enum.

If you check the MSDN documentation for the Keys enum, you'll see the following warning:

Do not use the values in this enumeration for combined bitwise operations. The values in the enumeration are not mutually exclusive.

As far as I can tell, the only values of the Keys enum that can be combined with other values are Shift, Ctrl and Alt.

See an extract from the enum:

[Flags]
[TypeConverter(typeof(KeysConverter))]
public enum Keys
{
    ...
    A = 65,
    B = 66,
    C = 67,
    ...
    Shift = 65536,
    Control = 131072,
    Alt = 262144
}

Upvotes: 3

Related Questions