Currently, I’m overriding the Form.ProcessDialogKey method inside my WinForms form to allow the user to directly select a tab page of a tab control inside the form when pressing Alt+1 … Alt+9.
I.e. pressing Alt+1 should select the first tab, Alt+2 the second tab, etc.
This is an excerpt of my code:
protected override bool ProcessDialogKey(Keys keyData)
{
if ((e.KeyData & Keys.Alt) == Keys.Alt)
{
if ((e.KeyData & Keys.D1) == Keys.D1) tabIndex = 0;
else if ((e.KeyData & Keys.D1) == Keys.D1) tabIndex = 0;
else if ((e.KeyData & Keys.D2) == Keys.D2) tabIndex = 1;
else if ((e.KeyData & Keys.D3) == Keys.D3) tabIndex = 2;
// ...
}
}
I discovered that my check give redundant results. E.g. when pressing Alt+3,
(e.KeyData & Keys.D3) == Keys.D3 // <<== TRUE.
is true, but also other checks are true, e.g.:
(e.KeyData & Keys.D1) == Keys.D1 // <<== also TRUE.
(e.KeyData & Keys.D0) == Keys.D0 // <<== also TRUE.
I do think this is quite logical, since the Keys enumeration does lot of bitwise combination of other Keys member values.
So I do unsertand why I get too much true results, I just do not know how to do a correct check.
My question:
Can I use the Form.ProcessDialogKey method at all to check for Alt+1…Alt+9 combination or should I choose another aproach?
(If there is another aproach, I would love to get a link to it)
Update 1:
It seems that if I revers the check order, i.e. first Keys.D9 and then down to Keys.D1 that the matching works better (correct?)
Using the & operator here is not correct. The Keys enumeration has the [Flags] attribute but it is a combination of flags and a value. Necessarily so, there are many more keys than bits in an int or long. Some bits indicate a modifier, like Keys.Alt, but the lower 16 bits are the key code and you need to use the == operator to compare it.
Consider this code to keep it DRY: