Để tạo ra Form hiển thị để nhập mã captcha bằng C#, ta cần sử dụng đoạn mã sau đây.
private Graphics g; WebBrowser _browser; Bitmap _bitmap; public int getXoffset(HtmlElement el) { //get element pos int xPos = el.OffsetRectangle.Left; //get the parents pos HtmlElement tempEl = el.OffsetParent; while (tempEl != null) { xPos += tempEl.OffsetRectangle.Left; tempEl = tempEl.OffsetParent; } return xPos; } public int getYoffset(HtmlElement el) { //get element pos int yPos = el.OffsetRectangle.Top; //get the parents pos HtmlElement tempEl = el.OffsetParent; while (tempEl != null) { yPos += tempEl.OffsetRectangle.Top; tempEl = tempEl.OffsetParent; } return yPos; } private void CaptureWebPage(string url) { if (_browser == null) { _browser = new WebBrowser(); string PostDataStr = ""; byte[] PostDataByte = Encoding.UTF8.GetBytes(PostDataStr); string AdditionalHeaders = "Content-Type: application/x-www-form-urlencoded" + Environment.NewLine; _browser.Navigate(url, "", PostDataByte, AdditionalHeaders); while (_browser.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); } if (_browser.ReadyState == WebBrowserReadyState.Complete) { cookies = _browser.Document.Cookie; using (g = _browser.CreateGraphics()) { int width = _browser.Document.Body.ScrollRectangle.Width; int height = _browser.Document.Body.ScrollRectangle.Height; _bitmap = new Bitmap(width, height); _browser.Size = _bitmap.Size; _browser.DrawToBitmap(_bitmap, _browser.Bounds); // _browser.Stop(); if (_bitmap == null) return; HtmlDocument doc = _browser.Document; HtmlElement captcha_el = doc.GetElementsByTagName("img")[0]; int x_pertage = 5; int y_pertage = 20; Bitmap bmp = new Bitmap((int)(_bitmap.Width / x_pertage), (int)(_bitmap.Height / y_pertage)); Graphics gp = Graphics.FromImage(bmp); gp.DrawImage(_bitmap, new Rectangle(-getXoffset(captcha_el), -getYoffset(captcha_el), bmp.Width * x_pertage, bmp.Height * y_pertage)); Size newsize = new Size(bmp.Width, bmp.Height); pictureBox1.Image = bmp; } } } }
Cách sử dụng
CaptureWebPage("Đường dẫn tới trang chứa hình Captcha");
Chúc các bạn thành công !!