2009-04-13 61 views

回答

20

刪除中間鼠標按鈕被點擊的標籤的最短代碼是通過使用LINQ。

確保事件連線了
this.tabControl1.MouseClick += tabControl1_MouseClick; 
而對於處理程序本身
private void tabControl1_MouseClick(object sender, MouseEventArgs e) 
{ 
    var tabControl = sender as TabControl; 
    var tabs = tabControl.TabPages; 

    if (e.Button == MouseButtons.Middle) 
    { 
    tabs.Remove(tabs.Cast<TabPage>() 
      .Where((t, i) => tabControl.GetTabRect(i).Contains(e.Location)) 
      .First()); 
    } 
} 
如果你是追求線條的量最少,這是一條線
tabControl1.MouseClick += delegate(object sender, MouseEventArgs e) { var tabControl = sender as TabControl; var tabs = tabControl.TabPages; if (e.Button == MouseButtons.Middle) { tabs.Remove(tabs.Cast<TabPage>().Where((t, i) => tabControl.GetTabRect(i).Contains(e.Location)).First()); } }; 
-1

你可以這樣做:

private void tabControl1_MouseClick(object sender, MouseEventArgs e) 
{ 
    if (e.Button == MouseButtons.Middle) 
    { 
      // choose tabpage to delete like below 
      tabControl1.TabPages.Remove(tabControl1.TabPages[0]); 
    } 
} 

基本上你只是迎頭趕上標籤控制鼠標點擊僅刪除頁面,如果被點擊中間的按鈕。

+1

這將不會關閉被點擊的標籤頁。這會讓我瘋狂,如果它刪除了第一個,不管我點擊了哪一個。 – Samuel 2009-04-13 20:50:57

+0

那麼你會改變它來選擇你想要擺脫的任何標籤。 – ryanulit 2009-04-14 14:00:24

6

解決方案,而LINQ不那麼緊湊和美觀,但也是實際的:

private void TabControlMainMouseDown(object sender, MouseEventArgs e) 
{ 
    var tabControl = sender as TabControl; 
    TabPage tabPageCurrent = null; 
    if (e.Button == MouseButtons.Middle) 
    { 
     for (var i = 0; i < tabControl.TabCount; i++) 
     { 
      if (!tabControl.GetTabRect(i).Contains(e.Location)) 
       continue; 
      tabPageCurrent = tabControl.TabPages[i]; 
      break; 
     } 
     if (tabPageCurrent != null) 
      tabControl.TabPages.Remove(tabPageCurrent); 
    } 
} 
2

D沒有足夠的分數來發表對所提供的解決方案的評論,但他們都遭受同樣的缺陷:已刪除選項卡中的控件未被釋放。

Regards

相關問題