0

I want to detect Alt, or Alt + some key, from within Form1_KeyPress. This is my code:

    private void Form1_KeyPress(object sender, KeyPressEventArgs e)
    {

        if (Control.ModifierKeys == Keys.Alt)
        {
            MessageBox.Show("Alt");
        }
        if (Control.ModifierKeys == Keys.Control)
        {
            MessageBox.Show("Control");
        }
    }

When I hit Ctrl + A for example, the second if triggers. However when I hit Alt + A for example, nothing happens. Why is that? is there some other way to trigger Alt from Form1_KeyPress? I don't want to trigger it from KeyDown in this instance.

spunit
  • 523
  • 2
  • 6
  • 23
  • In the standard case, you haven't reconfigured the form somehow, neither Alt nor Control will trigger the KeyPress event. You may rather want to try KeyDown. In KeyDown you will have the Modifier Keys already in the EventArgs also. – Ralf May 10 '22 at 16:56
  • I have Key Preview on, so Ctrl triggers. The thing is KeyPress happens before KeyDown, and I want to do certain things before everything else. – spunit May 10 '22 at 17:03
  • Its the other way round KeyDown->KeyPress->KeyUp. – Ralf May 10 '22 at 17:18
  • `KeyDown` is triggered before `KeyPress`. If you want to act before the keys are sent to the target, override `ProcessCmdKey` instead. You get all keys before any event is raised. – Jimi May 10 '22 at 17:20
  • If you put a MessageBox in both, KeyPress will be the first to show up... – spunit May 10 '22 at 17:26
  • Using MessageBox here might be part of the problem. I can think of multiple ways to outsmart yourself with it. Hitting a modifier key will trigger a key event itself. Showing a messagebox then and therefore taking away the focus from the form will direct the next key click somewher else. – Ralf May 10 '22 at 17:35
  • Ok. Then ProcessCmdKey seems promising. I just tried it out but I need to do stuff like e.Handled = true; or e.SuppressKeyPress = true; Can similar things be made with ProcessCmdKey? – spunit May 10 '22 at 17:51
  • if you want to supress any handling a `return true` from ProcessCmdKey should just do that. Try that if it does not yield the needed thing, maybe because of special key combinations or your need to also suppress it for child controls a look at an IMessageFilter to suppress that would be the next thing. – Ralf May 10 '22 at 18:19
  • Probably want `if (Control.ModifierKeys | Keys.Alt != 9)` also `ALT` triggers a system key, so you might need to catch `KeyDown` instead. Alternatively you can override `ProcessDialogChar` – Charlieface May 10 '22 at 20:25
  • Thanks for your help, I think I'll try doing it in KeyDown for now. – spunit May 10 '22 at 21:59

0 Answers0