C# Tab switching in TabControl

后端 未结 2 877
一整个雨季
一整个雨季 2020-12-21 05:32

Iam facing such problem, which I find hard to overcome. In WinForms I got a TabControl with n TabPages. I want to extend the Ctrl+Tab / Ctrl+Shift+Tab switching. so I wrote

相关标签:
2条回答
  • 2020-12-21 06:02

    You need to derive from TabControl and override ProcessCmdKey, virtual method in order to override the Ctrl-Tab behavior.

    Example:

    public class ExtendedTabControl: TabControl
    {
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == (Keys.Control | Keys.Tab))
            {
                // Write custom logic here
                return true;
            }
            if (keyData == (Keys.Control | Keys.Shift | Keys.Tab))
            {
                // Write custom logic here, for backward switching
                return true;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }
    }
    
    0 讨论(0)
  • 2020-12-21 06:07

    TabControl has fairly unusual processing to handle the Tab key. It overrides the ProcessKeyPreview() method to detect Ctrl/Shift/Tab, then implements the tab selection in its OnKeyDown() method. It does this so it can detect the keystroke both when it has the focus itself as well as any child control. And to avoid stepping on custom Tab key processing by one of its child controls. You can make it work by overriding ProcessCmdKey() but then you'll break child controls that want to respond to tabs.

    Best thing to do is to override its OnKeyDown() method. Add a new class to your project and paste the code shown below. Compile. Drop the new tab control from the top of the toolbox onto your form.

    using System;
    using System.Windows.Forms;
    
    class MyTabControl : TabControl {
      protected override void OnKeyDown(KeyEventArgs e) {
        if (e.KeyCode == Keys.Tab && (e.KeyData & Keys.Control) != Keys.None) {
          bool forward = (e.KeyData & Keys.Shift) == Keys.None;
          // Do your stuff
          //...
        }
        else base.OnKeyDown(e);
      }
    }
    

    Beware that you also ought to consider Ctrl+PageUp and Ctrl+PageDown.

    0 讨论(0)
提交回复
热议问题