承接前兩篇資料結構與核心邏輯,本文展示如何在 WinForms/WebForms 頁面中整合 HistoryManager (基於 LinkedList<T>) 實現前進/後退按鈕狀態同步與頁面載入。
public partial class BrowserForm : Form
{
private readonly HistoryManager _history = new HistoryManager();
private void AddHistory(string title, string html, string url)
{
_history.Add(new HistoryItem { Title = title, Html = html, Url = url });
UpdateNavButtons();
}
private void BtnBack_Click(object sender, EventArgs e)
{
_history.Back();
LoadCurrentPage();
UpdateNavButtons();
}
private void BtnForward_Click(object sender, EventArgs e)
{
_history.Forward();
LoadCurrentPage();
UpdateNavButtons();
}
private void LoadCurrentPage()
{
var item = _history.Current;
if (item != null)
{
webBrowser.DocumentText = item.Html;
txtUrl.Text = item.Url;
Text = item.Title;
}
}
private void UpdateNavButtons()
{
btnBack.Enabled = _history.CanBack;
btnForward.Enabled = _history.CanForward;
}
}
public class HistoryManager
{
private readonly LinkedList _list = new LinkedList();
private LinkedListNode _current;
public HistoryItem Current => _current?.Value;
public bool CanBack => _current?.Previous != null;
public bool CanForward => _current?.Next != null;
public void Add(HistoryItem item)
{
if (_current != null)
{
// 移除前進歷史 (C, D 被捨棄)
while (_current.Next != null)
_list.RemoveLast();
}
_current = _list.AddLast(item);
}
public void Back() => _current = _current?.Previous;
public void Forward() => _current = _current?.Next;
}
| 操作序列 | 歷史清單狀態 | 當前位置 |
|---|---|---|
| 造訪 A → B → C → D | A - B - C - D | D |
| 後退到 B | A - B - C - D | B |
| 造訪 E | A - B - E (C, D 移除) | E |
LinkedList<T> 的 O(1) 節點插入/刪除/前後導航特性,完美契合瀏覽器歷史需求。實務中尚需處理:快取策略、序列化持久化、多索引標籤隔離、前進/後退手勢支援等。