C# Tab switching in TabControl

有些话、适合烂在心里 提交于 2019-11-28 09:00:13

问题


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 some code which works fine as long as the focus is on TabControl or on the Form. When application focus is INSIDE of TabPage (for example on a button which is placed inside of TabPage), while pressing Ctrl+Tab, my code is ignored and TabControl skips to TabPage on his own (avoiding my code).

Anyone idea ?


回答1:


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);
    }
}



回答2:


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.



来源:https://stackoverflow.com/questions/1872972/c-sharp-tab-switching-in-tabcontrol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!