65.9K
CodeProject is changing. Read more.
Home

Determining which TabPage was clicked

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Nov 8, 2011

CPOL

1 min read

viewsIcon

31581

A binary search technique to determine which TabPage of a TabControl was clicked

One of the many little WinForms applications I am working on has a TabControl with a variable number of TabPages (perhaps many). I want to allow the user to click and drag a tab to reorder the TabPages. A quick look at the documentation revealed nothing, and a quick search online revealed that this is a common problem. The situation is that TabPages don't receive mouse events, the TabControl (their parent) does, then you have to use methods of the TabControl to determine which TabPage was clicked. I glanced at two articles here on The Code Project to see how others had implemented this, and they provided a good starting point, but (being me) I came up with my own solution. What I want is to get the index of a TabPage on MouseDown and again on MouseUp. At first, I implemented a simple iterative search for the TabPage, but today I realized that a binary search technique would be better (at least with a great number of TabPages), so I changed it to:
private static int
GetTabIndexAt
(
  System.Windows.Forms.TabControl TabControl
,
  System.Drawing.Point            Point
)
{
  int result = -1 ;

  if ( TabControl != null )
  {
    int lo = 0 ;
    int hi = TabControl.TabPages.Count - 1 ;

    while ( ( result == -1 ) && ( lo <= hi ) )
    {
      int mid = lo + ( hi - lo ) / 2 ;
      System.Drawing.Rectangle rect = TabControl.GetTabRect ( mid ) ;

      if ( rect.Contains ( Point ) )
      {
        result = mid ;
      }
      else if ( ( Point.X < rect.Left ) || ( Point.Y < rect.Top ) )
      {
        hi = mid - 1 ;
      }
      else
      {
        lo = mid + 1 ;
      }
    }
  }

  return ( result ) ;
}
Edit: Added test of ( Point.Y < rect.Top ) to handle left-aligned tabs -- but it still only works with one row or columns of Tabs.