首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

仿 QQ 面板舉一反三:拉幕式視窗實作 (3) — 完整事件邏輯與 UserControl 載入

     編輯:關於C語言

核心變數與屬性


private string[] _Module;
private int _ModuleButtonWidth = 25;
public string[] Module {
    get { return _Module; }
    set { _Module = value; }
}

Form_Load:動態建立模組按鈕


private void Form1_Load(object sender, EventArgs e) {
    this.panel1.BorderStyle = BorderStyle.None;
    Module = new[] { "模組1", "模組2", "模組3", "模組4", "模組5" };
    for (int i = 0; i < Module.Length; i++) {
        Button btn = new Button {
            FlatStyle = FlatStyle.Popup,
            Width = _ModuleButtonWidth,
            Height = panel1.Height,
            Name = "Button" + i,
            Text = Module[i],
            Left = panel1.Width - _ModuleButtonWidth * (Module.Length - i)
        };
        btn.Click += btn_Click;
        panel1.Controls.Add(btn);
    }
}

btn_Click:切換面板與載入 UserControl


private void btn_Click(object sender, EventArgs e) {
    bool found = false;
    // 移除舊面板
    for (int i = 0; i < panel1.Controls.Count; i++) {
        if (panel1.Controls[i] is Panel) {
            panel1.Controls.RemoveAt(i--);
        }
    }
    // 重新定位按鈕並載入對應面板
    for (int i = 0; i < panel1.Controls.Count; i++) {
        if (panel1.Controls[i] is Button btn) {
            btn.Left = found 
                ? panel1.Width - _ModuleButtonWidth * (Module.Length - i)
                : _ModuleButtonWidth * i;
            if (btn.Name == ((Button)sender).Name) {
                found = true;
                Panel p = new Panel {
                    BackColor = Color.AliceBlue,
                    Left = _ModuleButtonWidth * (i + 1),
                    Width = panel1.Width - _ModuleButtonWidth * Module.Length,
                    Height = panel1.Height
                };
                switch (i) {
                    case 0: p.Controls.Add(new ucPart1()); break;
                    case 1: p.Controls.Add(new ucPart2()); break;
                    case 2: p.Controls.Add(new ucPart3()); break;
                    case 3: p.Controls.Add(new ucPart4()); break;
                    case 4: p.Controls.Add(new ucPart5()); break;
                }
                panel1.Controls.Add(p);
            }
        }
    }
}

完整原始碼下載

https://files.cnblogs.com/KenBlove/WindowsApplication1.7z

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved