2013-05-14 94 views
-2

有沒有辦法左對齊工具欄(不離開「空格」)的代碼? enter image description here通過代碼左對齊工具欄

(比如,點擊該按鈕2時) enter image description here

PS
此外這種情況

enter image description here
爲 「左對齊」 是指:
enter image description here

+0

左對齊工具欄意味着你需要改變的MenuStrip類似的東西現在的位置? – 2013-05-14 10:22:54

+0

我需要從第一個圖像的工具欄像第二個圖像的工具欄一樣對齊。 – serhio 2013-05-14 10:23:44

+0

就這樣,我可以確定我已經理解了這個問題,是否當你停靠(DockStyle)時,你不能再應用一個寬度?因此,寬度比你想要的寬得多。 – Dave 2013-05-14 10:52:47

回答

0

更新

根據您的標準改變相當戲劇性,下面是一些代碼,它會讓你去。它不完美,甚至接近完美!

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
     _otherStrips = new List<OtherStrips>(); 
    } 

    private int _currentHeight = 0; 
    private List<OtherStrips> _otherStrips; 

    private void button1_Click(object sender, EventArgs e) 
    { 
     foreach (var c in panel1.Controls) 
     { 
      if (c is ToolStrip) 
      { 
       ToolStrip ts = (ToolStrip)c; 
       _otherStrips.Add(new OtherStrips() { Top = ts.Top, Width = ts.Width, Name = ts.Name }); 
       MoveToPosition(ts); 
      } 
     } 
    } 

    private void MoveToPosition(ToolStrip toolStrip) 
    { 
     bool isInline; 
     toolStrip.Left = GetWidth(toolStrip, out isInline); 

     if (isInline) 
      toolStrip.Top = GetTop(toolStrip); 
    } 

    private int GetWidth(ToolStrip ts, out bool isInline) 
    { 
     int result = 0; 
     isInline = false; 
     foreach (var item in _otherStrips) 
     { 
      if (item.Name == ts.Name) 
       continue; 

      if (item.Top == ts.Top) 
      { 
       isInline = true; 
       break; 
      } 
     } 

     if (!isInline) 
      return result; 

     foreach (var item in _otherStrips) 
     { 
      if (item.Width == ts.Width) 
       result += item.Width; 
     } 

     return result + 22;//hack since the width is out by about 22pixels. Not going to spend any time fixing this 
    } 

    private int GetTop(ToolStrip ts) 
    { 
     foreach (var item in _otherStrips) 
     { 
      if (item.Name == ts.Name) 
       continue; 

      if (item.Top == ts.Top) 
       return item.Top; 
     } 

     _currentHeight += ts.Height; 
     return _currentHeight; 
    } 
} 

struct OtherStrips 
{ 
    public int Top { get; set; } 
    public int Width { get; set; } 
    public string Name { get; set; } 
} 
+0

看到我的編輯...還有,可能有不定數量的工具欄... – serhio 2013-05-14 12:08:11

+0

@serhio,我更新了我的答案。這是不完美的,但一個良好的開始 – Dave 2013-05-15 07:54:04

+0

是不是我採取的解決方案,但我將標記爲答案... – serhio 2013-05-22 08:43:41

0

你可以用它來對準留下您的ToolStrip

toolStrip1.Location = new Point(0, toolStrip1.Location.Y); 
+0

通過替換名稱使用toolStrip2和toolStrip3相同的代碼..我測試過了,它的工作: ) – Jexfer 2013-05-14 11:15:23

+0

看到我的編輯,這不適用於可變數量的工具欄... – serhio 2013-05-14 12:09:40