Stringeater
Stringeater

Reputation: 170

C# WinForms TabStrip control: no accelerator

I am using a tab strip control on a WinForms form. I make use of keyboard accelerators as much as possible. When I set the Text property of a TabPage to e.g. &Documents, the text on the tab is literally &Documents instead of the letter D being underlined.

The help about TabStrip and TabPage doesn't cover this topic. The property ShowKeyboardCues is read-only. Google is helpless.

Can anyone give me a hint how to show accelerators?

Upvotes: 0

Views: 313

Answers (2)

Caius Jard
Caius Jard

Reputation: 74660

How can I set up keyboard shortcuts for a Windows Forms TabControl? gives tips on setting up keyboard shortcuts for it.. In terms of showing an accelerator though, you'll have to draw them yourself

Set the tabControl's DrawMode to OwnerDrawFixed then do some code to draw the tabs, for example (I had to try hard to make it this ugly)

    private void tabControl1_DrawItem(object sender, DrawItemEventArgs e)
    {
        //Change appearance of tabcontrol
        Brush backBrush = Brushes.Red;
        Brush foreBrush = Brushes.Blue;
        e.Graphics.FillRectangle(backBrush, e.Bounds);

        Rectangle r = e.Bounds;
        r = new Rectangle(r.X, r.Y + 3, r.Width, r.Height - 3);
        e.Graphics.DrawString("my label", e.Font, foreBrush, r);
        var sz = e.Graphics.MeasureString("my ", e.Font);
        e.Graphics.DrawString("_", Font, foreBrush, r.X + sz.Width - 2, r.Y + 2);
    }

enter image description here

Joking aside, setting up some ugly colors does help you see where the bounds of the drawing area are etc. I'm sure you'll tart it up..

Upvotes: 1

oldcoder
oldcoder

Reputation: 342

Neither of these controls supports that functionality. It is possible to simulate it, but it is a long and complicated task that I would not recommend because it is non-standard functionality. As a result it is unlikely that anyone would expect it to occur. On the other hand, changing tabs using Ctrl+Tab is standard behaviour so is already automatically supported.

If you did want to do this, you would need to:

  • Subclass the Control
  • Override the painting and draw the text on the tab yourself
  • Get a preview of the keydown event and use that to determine if the key combination you wanted was pressed
  • Select the correct tab programmatically based on the keypress that you have intercepted

As I say, I would not recommend this because it is not normal behaviour for that control and because the complexity means that it is likely to be buggy. But it is possible...

Upvotes: 1

Related Questions