在 WinForm 專案中需要從網頁獲取驗證碼圖片。直接用 WebClient 下載圖片 URL 存在兩大問題:驗證碼每次請求可能不同,且難以同步 WebBrowser 的 Cookie/Session。改用底層 WebRequest 雖可行但較繁瑣。最終採用「截圖法」:讓 WebBrowser 載入頁面,將驗證碼圖片元素定位至左上角並置頂,再呼叫 DrawToBitmap 截取。
src 屬性以 RandomImage.aspx 結尾。遍歷 WebBrowser.Document.Images 找到該元素。position: absolute; z-index: 9999; top: 0px; left: 0px,確保它位於視窗左上角且不被遮擋。ClientRectangle 建立 Bitmap,呼叫 WebBrowser.DrawToBitmap 繪製,最後指派給 PictureBox 顯示。private void button1_Click(object sender, EventArgs e) {
var wb = new WebBrowser();
wb.Navigate("https://www.jcard.cn/Charge/UCardDirectCharge.aspx?category=AAWYVVWYKV&product=AAWYVVWYKV010CV");
while (wb.ReadyState != WebBrowserReadyState.Complete) Application.DoEvents();
foreach (HtmlElement img in wb.Document.Images) {
if (img.GetAttribute("src").ToLower().EndsWith("randomimage.aspx")) {
img.Style = "position: absolute; z-index: 9999; top: 0px; left: 0px";
var bmp = new Bitmap(img.ClientRectangle.Width, img.ClientRectangle.Height);
wb.DrawToBitmap(bmp, new Rectangle(Point.Empty, img.ClientRectangle.Size));
pictureBox1.Image = bmp;
break;
}
}
}
DrawToBitmap 是隱藏方法,IntelliSense 不提示。實測發現:若 WebBrowser 控件顯示在表單上,截圖會全白;若不加入表單(僅在記憶體中建立),截圖正常。原因不明,僅能作為經驗法則使用。


