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

QQ 表情彈出框實現:WebBrowser + 動態 HTML 分頁,高性能替代 PictureBox 方案

     編輯:關於.NET

方案演進

  • 方案一:Panel 動態創建 PictureBox 載入 GIF → **極慢**,放棄
  • 方案二:WebBrowser 載入本地 HTML 模板 → **極快**,採用

核心實現

1. HTML 模板 + XML 配置

  • template.html:包含表格佔位符 $TableRow$、導航佔位符 $Navigation$、顏色佔位符 $BgColor$
  • face.xml:表情文件名列表

2. 動態生成 HTML (分頁邏輯)

private void LoadQQFace(int page, int rows, int cols) {
    currentPage = page;
    string tpl = File.ReadAllText("template.html");
    DataSet ds = new DataSet(); ds.ReadXml("face.xml");
    DataTable dt = ds.Tables[0];
    int total = dt.Rows.Count;
    pageSize = (total + rows * cols - 1) / (rows * cols);

    // 構建表格行
    string tableRows = "";
    for (int i = 1; i <= rows; i++) {
        string tr = "";
        for (int j = 1; j <= cols; j++) {
            int idx = (i-1)*cols + (page-1)*rows*cols + j;
            if (idx < total) {
                string img = Application.StartupPath + @"\faces\" + dt.Rows[idx][0];
                tr += $"

"; } else tr += ""; } tr += ""; tableRows += tr; } // 替換佔位符 tpl = tpl.Replace("$TableRow$", tableRows) .Replace("$LeftLimt$", (29 * (cols/2)).ToString()) .Replace("$RightLimt$", ((cols-3)*29).ToString()) .Replace("$BgColor$", ColorTranslator.ToHtml(BackColor)) .Replace("$Navigation$", $""); // 寫入臨時文件並導航 string temp = Path.GetTempPath() + "tempHtmlFile.html"; File.WriteAllText(temp, tpl); webBrowser1.Navigate(temp); webBrowser1.DocumentCompleted += WebBrowser1_DocumentCompleted; // 自適應窗體大小 Width = 29 * cols + 21; Height = 29 * rows + 80; }

3. 分頁事件綁定 (DocumentCompleted 中)

void WebBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
    var doc = webBrowser1.Document;
    var prev = doc.GetElementById("linkPrev");
    var next = doc.GetElementById("linkNext");
    
    if (prev != null) {
        prev.Click -= LinkPrev_Click;
        if (currentPage > 1) prev.Click += LinkPrev_Click;
    }
    if (next != null) {
        next.Click -= LinkNext_Click;
        if (currentPage < pageSize) next.Click += LinkNext_Click;
    }
}

void LinkPrev_Click(object sender, HtmlElementEventArgs e) => LoadQQFace(currentPage - 1, 8, 9);
void LinkNext_Click(object sender, HtmlElementEventArgs e) => LoadQQFace(currentPage + 1, 8, 9);

效果展示

待解決問題

點擊表情如何插入聊天輸入框?需 JS 與 WinForm 交互 (window.external 或 ObjectForScripting),歡迎交流。

源碼下載

QQFace.rar

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