简体   繁体   中英

Optional Override on a custom control

I have a custom TabControl which has code both to prevent the user from navigating using Tab shortcuts, and to remove the tab headers. There's a situation in which I want to still prevent tab navigation, but show the tab headers, so I had the idea of creating an attribute for the the custom control and only applying the code that hides the headers when this attribute is true , but I got the solution for removing tab headers from here and I don't fully understand it.

I tried placing the code inside an if with my attribute, but this crashes my visual studio. I suppose that it is because doing this I will be overriding a necessary code with an empty procedure when useHide == false , so, how do I make so when useHide == false it runs the regular inherited code instead of overriding it?

    public class ExTabControl : TabControl
    {
        private bool useHide = true;

        [Description("Hide tab headers."), Category("Appearance")]
        public bool UseHideTabs
        {
            get => useHide;
            set => useHide = value;
        }

        /// Intercept any key combinations that would change the active tab.
        protected override void OnKeyDown(KeyEventArgs e)
        {
            bool changeTabKeyCombination =
                (e.Control
                    && (e.KeyCode == Keys.Tab
                        || e.KeyCode == Keys.Next
                        || e.KeyCode == Keys.Prior));

            if (!changeTabKeyCombination)
            {
                base.OnKeyDown(e);
            }
        }

        private const int TCM_ADJUSTRECT = 0x1328;

        protected override void WndProc(ref Message m)
        {
            if (useHide == true)
            {
                // Hide the tab headers at run-time
                if (m.Msg == TCM_ADJUSTRECT && !DesignMode)
                {
                    m.Result = (IntPtr)1;
                    return;
                }

                // call the base class implementation
                base.WndProc(ref m);
            }
        }
    }

.NET framework 4.7.2, Visual Studio 2019, Winforms Application

Your are missing call of base method when useHide is false, try this method instead.

protected override void WndProc(ref Message m)
{
    // Hide the tab headers at run-time
    if (useHide && m.Msg == TCM_ADJUSTRECT && !DesignMode)
    {
        m.Result = (IntPtr)1;
        return;
    }

    // call the base class implementation
    base.WndProc(ref m);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM