Search code examples
c#.netwinformsmdichild

how to prevent a certain mdichild form from getting focus/activation when switching between other mdichild forms using Ctrl+Tab? C#


In my mdi application i have four mdichild forms, one of them is used as a background and holding some controls..

How to prevent this background mdichild form from getting focus/activation when switching between other mdichild forms using Ctrl+Tab?

In other word how to skip this background mdi child form from the Ctrl+Tab sequence? and also make its z-order to be the last one so that it doesn't hide other mdichild forms when switching between them?

thanks in advance.


Solution

  • By overriding Form.ProcessCmdKey and skip the background form.

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if ((keyData & Keys.Tab) == Keys.Tab && (keyData & Keys.Control) == Keys.Control)
            {
    
                Form nextForm = GetNexMdiChildForm();
                if (nextForm != null)
                {
                    nextForm.Activate();
                    return false;
                }
            }
    
            return base.ProcessCmdKey(ref msg, keyData);
        }
    
        private Form GetNexMdiChildForm()
        {
            //get current form index
            Form currentForm = this.ActiveMdiChild;
            int currentFormIndex = Array.IndexOf(this.MdiChildren, currentForm);
    
            //get next form index
            int nextFormIndex = currentFormIndex + 1;
            if (this.MdiChildren.Length == nextFormIndex)
            {
                nextFormIndex = 0;
            }
    
            //check if next form is Form 3
            if (this.MdiChildren[nextFormIndex] == background_mdichild_form )
            {
                nextFormIndex++;
                if (this.MdiChildren.Length == nextFormIndex)
                {
                    nextFormIndex = 0;
                }
            }
            return MdiChildren[nextFormIndex];
        }