How to display only my application forms when pressing Key1 + Key2, just like Alt + Tab does in Windows?

348 Views Asked by At

My application has several forms. What I want to do is to be able to switch between them (and only between them) using a pair of predefined keys (say Keys.A + Keys.B), just like ALT + TAB does for Windows (windows are shown in foreground). I tried getting the list of forms and then programmatically call Alt + Tab, but, as expected, this allows to switch between all open windows and not only the ones belonging to the application.

Thanks for any help!

2

There are 2 best solutions below

2
On

You could implement IMessageFilter and add it to your Application, then globally process the messages of your application.

Here is how you do that.

public class MessageFilter : IMessageFilter
{
    public bool PreFilterMessage(ref Message m)
    {
        switch ((WindowsMessage)m.Msg)
        {
            case WindowsMessage.WM_KEYDOWN:
            case WindowsMessage.WM_SYSKEYDOWN:
                {
                    if (((int)m.WParam | ((int)Control.ModifierKeys)) != 0)
                    {
                        Keys keyData = (Keys)(int)m.WParam;

                        var activeForm = Form.ActiveForm;
                        var forms = Application.OpenForms.Cast<Form>().Where(x => x.Visible).ToArray();
                        int active = Array.IndexOf(forms, activeForm);
                        if (keyData == Keys.A)
                        {
                            int next = (active + 1)%forms.Length;
                            forms[next].Activate();//Activate next
                        }
                        else if (keyData == Keys.B)
                        {
                            int prev = (active - 1) % forms.Length;
                            forms[prev].Activate();//Activate previous
                        }

                    break;
                }
        }

        return false;
    }
}

class MainForm : Form
{
    protected override void OnLoad(EventArgs e)
    {
        Application.AddMessageFilter(new MessageFilter());
    }
}

You can find WindowsMessage enumeration here.

5
On

If you have multiple windows (forms) opened and they have normal caption or belong to MDI, then Ctrl+F6 is a standard shortcut to switch between them.

Otherwise, making a hotkey, to switch between forms is pretty trivial task:

  • all forms have to have KeyPreview = true and KeyDown | KeyUp event;
  • all forms instances have to be accessible (one possibility is Application.OpenForms);
  • when hotkey is pressed, find next / previous window and make it active.