How to get Captcha image from DotNetBrowser Control c# and set to pictureBox - webbrowser-control

I am using DotNetBrowser Control in my c# desktop application. I am not able to get captcha image using this.
It is easy in Webbrowser control but in DotNetBrowser I don't know how to do so in c#
https://dotnetbrowser.support.teamdev.com/support/solutions/9000111998
This code is working if I am using Webbrowser control
private Image getCaptcha()
{
HtmlElement ement = webBrowser1.Document.GetElementById("imgCaptcha");
if (ement == null)
{
return null;
}
mshtml.HTMLWindow2 w2 = (mshtml.HTMLWindow2)webBrowser1.Document.Window.DomWindow;
w2.execScript("var ctrlRange = document.body.createControlRange();
ctrlRange.add(document.getElementById('imgCaptcha'));
ctrlRange.execCommand('Copy');", "javascript");
return Clipboard.GetImage();
}
I need similar code in DotNetBrowser control

You can use the 'Browser.ImageProvider.GetImage' method to get the screenshot of the page and then crop this image to the bounds of the captcha image.
The only restriction is that the Browser should use the lightweight rendering mode as getting an image is unavailable in the heavyweight mode.
The described approach may look like the following source code:
browserView = new WinFormsBrowserView(BrowserFactory.Create(BrowserType.LIGHTWEIGHT));
//...
browserView.Browser.SetSize(1024, 768);
Bitmap screenshot = browserView.Browser.ImageProvider.GetImage() as Bitmap;
DOMElement captchaElement = browserView.Browser.GetDocument().GetElementById("imgCaptcha");
pictureBox1.Image = screenshot?.Clone(captchaElement.BoundingClientRect, screenshot.PixelFormat);

Related

Background Image Is Other Image Vb.net [duplicate]

In my C# Form I have a Label that displays a download percentage in the download event:
this.lblprg.Text = overallpercent.ToString("#0") + "%";
The Label control's BackColor property is set to be transparent and I want it to be displayed over a PictureBox. But that doesn't appear to work correctly, I see a gray background, it doesn't look transparent on top of the picture box. How can I fix this?
The Label control supports transparency well. It is just that the designer won't let you place the label correctly. The PictureBox control is not a container control so the Form becomes the parent of the label. So you see the form's background.
It is easy to fix by adding a bit of code to the form constructor. You'll need to change the label's Parent property and recalculate it's Location since it is now relative to the picture box instead of the form. Like this:
public Form1() {
InitializeComponent();
var pos = label1.Parent.PointToScreen(label1.Location);
pos = pictureBox1.PointToClient(pos);
label1.Parent = pictureBox1;
label1.Location = pos;
label1.BackColor = Color.Transparent;
}
Looks like this at runtime:
Another approach is to solve the design-time problem. That just takes an attribute. Add a reference to System.Design and add a class to your project, paste this code:
using System.ComponentModel;
using System.Windows.Forms;
using System.Windows.Forms.Design; // Add reference to System.Design
[Designer(typeof(ParentControlDesigner))]
class PictureContainer : PictureBox {}
You can just use
label1.Parent = pictureBox1;
label1.BackColor = Color.Transparent; // You can also set this in the designer, as stated by ElDoRado1239
You can draw text using TextRenderer which will draw it without background:
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
TextRenderer.DrawText(e.Graphics,
overallpercent.ToString("#0") + "%",
this.Font,
new Point(10, 10),
Color.Red);
}
When overallpercent value changes, refresh pictureBox:
pictureBox1.Refresh();
You can also use Graphics.DrawString but TextRenderer.DrawText (using GDI) is faster than DrawString (GDI+)
Also look at another answer here and DrawText reference here
For easy for your design.
You can place your label inside a panel. and set background image of panel is what every image you want. set label background is transparent
After trying most of the provided solutions without success, the following worked for me:
label1.FlatStyle = FlatStyle.Standard
label1.Parent = pictureBox1
label1.BackColor = Color.Transparent
You most likely not putting the code in the load function. the objects aren't drawn yet if you put in the form initialize section hence nothing happens.
Once the objects are drawn then the load function runs and that will make the form transparents.
private void ScreenSaverForm_Load(object sender, EventArgs e)
{
label2.FlatStyle = FlatStyle.Standard;
label2.Parent = pictureBox1;
label2.BackColor = Color.Transparent;
}
One way which works for everything, but you need to handle the position, on resize, on move etc.. is using a transparent form:
Form form = new Form();
form.FormBorderStyle = FormBorderStyle.None;
form.BackColor = Color.Black;
form.TransparencyKey = Color.Black;
form.Owner = this;
form.Controls.Add(new Label() { Text = "Hello", Left = 0, Top = 0, Font = new Font(FontFamily.GenericSerif, 20), ForeColor = Color.White });
form.Show();
Using Visual Studio with Windows Form you may apply transparency to labels or other elements by adding using System.Drawing; into Form1.Designer.cs This way you will have Transparency available from the Properties panel ( in Appearance at BackColor ). Or just edit code in Designer.cs this.label1.BackColor = System.Drawing.Color.Transparent;

Create PDF file with images in WinRT

How I can create PDF files from a list of image in WinRT. I found something similar for windows phone 8 here("Converting list of images to pdf in windows phone 8") But I am looking for a solution for windows 8. If anyone of having knowledge about this please share your thoughts with me.
Try http://jspdf.com/
This should work on WinJS, but I haven't tested it. In a XAML app you can try to host a web browser control with a jsPDF-enabled page.
ComponentOne has now released the same PDF library that they had in Windows Phone for Windows Runtime. Tho it's not open source, of course.
Amyuni PDF Creator for WinRT (a commercial library) could be used for this task. You can create a new PDF file by creating a new instance of the class AmyuniPDFCreator.IacDocument, then add new pages with the method AddPage, and add pictures to each page by using the method IacPage.CreateObject.
The code in C# for adding a picture to a page will look like this:
public IacDocument CreatePDFFromImage()
{
IacDocument pdfDoc = new IacDocument();
// Set the license key
pdfDoc.SetLicenseKey("Amyuni Tech.", "07EFCD0...C4FB9CFD");
IacPage targetPage = pdfDoc.GetPage(1); // A new document will always be created with an empty page
// Adding a picture to the current page
using (Stream imgStrm = await Windows.ApplicationModel.Package.Current.InstalledLocation.OpenStreamForReadAsync("pdfcreatorwinrt.png"))
{
IacObject oPic = page.CreateObject(IacObjectType.acObjectTypePicture, "MyPngPicture");
BinaryReader binReader = new BinaryReader(imgStrm);
byte[] imgData = binReader.ReadBytes((int)imgStrm.Length);
// The "ImageFileData" attribute has not been added yet to the online documentation
oPic.AttributeByName("ImageFileData").Value = imgData;
oPic.Coordinates = new Rect(100, 2000, 1200, 2000);
}
return pdfDoc;
}
Disclaimer: I currently work as a developer of the library
For an "open source" alternative it might be better for you to rely on a web service that creates the PDF file using one of the many open source libraries available.
I think this may help you if you want to convert an image (.jpg) file to a PDF file.
Its working in my lab.
string source = "image.jpg";
string destinaton = "image.pdf";
PdfDocument doc = new PdfDocument();
doc.Pages.Add(new PdfPage());
XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[0]);
XImage img = XImage.FromFile(source);
xgr.DrawImage(img, 0, 0);
doc.Save(destinaton);
doc.Close();
Thanks.

How to set Background of a Button without flicker?

I am trying to change the Background of a button to an image source. I want to load that image in memory when we navigate to the page so that it doesn't flicker the first time it shows.
On Windows Phone, I was able to create the image source as such:
StreamResourceInfo resourceInfo = Application.GetResourceStream(uri);
BitmapImage bitmapSource = new BitmapImage();
// Avoid flicker by not delay-loading.
bitmapSource.CreateOptions = BitmapCreateOptions.None;
bitmapSource.SetSource(resourceInfo.Stream);
imageSource = bitmapSource;
I tried something similar in my Windows 8 Store app:
BitmapImage bitmapSource = new BitmapImage();
bitmapSource.CreateOptions = BitmapCreateOptions.None;
bitmapSource.UriSource = uri;
imageSource = bitmapSource;
but the same problem occurs. The button already has a different image as the Background, and on a certain event I would like it to change to the new background. But when I change the source, a noticeable flicker is observed. I'm assuming this is because the image is not yet in memory, as the issue goes away the second time the image source is modified.
Anyone know a solution? I need to somehow force the loading of this image.
Thanks!
If you use the SetSourceAsync method on the BitmapImage and await it before you attach it to the image source you should not see the flicker:-
// Ensure the stream is disposed once the image is loaded
using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
// Set the image source to the selected bitmap
BitmapImage bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(fileStream);
imageSource = bitmapImage;
}
The MSDN docs have some more info on this
Thanks Ross, but what I ended up doing instead is I preloaded the half dozen or so bitmaps I needed by using similar code to what you had above, except from resource of course. I did this asynchronously when the page loaded, and then when I set the ImageSource on the button background, I used the already preloaded bitmaps. That way I know I'm not allocated a new chunk of memory for every instance of the bitmap.

Using WriteableBitmapEx

I am currently developing metro apps and I need to write text On images.
I found this http://writeablebitmapex.codeplex.com/
But I am new to XAML and dosent know how to use it specifically.
So can anyone say me how do I use it in order to write text on image.
As I have asked this question on MSDN but I have no reply yet.
Edit:
If I use as Muad'Dib I am getting the error as seen in below screenshot:
The Error is: 'Writeable Bitmap Extensions' is ambiguous in the namespace 'System.Windows.Media.Imaging'
there is one possible solution in the Discussions area for WriteableBitmapEx
here is the code from that "article":
public static void DrawText(this WriteableBitmap wBmp,Point at, string text,double fontSize,Color textColor)
{
TextBlock lbl = new TextBlock();
lbl.Text = text;
lbl.FontSize = fontSize;
lbl.Foreground = new SolidColorBrush(textColor);
WriteableBitmap tBmp = new WriteableBitmap(lbl, null);
wBmp.Blit(at, tBmp, new Rect(0, 0, tBmp.PixelWidth, tBmp.PixelHeight), Colors.White, System.Windows.Media.Imaging.WriteableBitmapExtensions.BlendMode.Alpha);
}

How can I programmatically create a screen shot of a given Web site?

I want to be able to create a screen shot of a given Web site, but the Web site may be larger than can be viewed on the screen. Is there a way I can do this?
Goal is to do this with .NET in C# in a WinForms application.
There are a few tools.
The thing is, you need to render it in some given program, and take a snapshot of it.
I don't know about .NET but here are some tools to look at.
KHTML2PNG
imagegrabwindow() (Windows PHP Only)
Create screenshots of a web page using Python and QtWebKit
Website Thumbnails Service
Taking automated webpage screenshots with embedded Mozilla
I just found out about the website browsershots.org which generates screenshots for a whole bunch of different browsers. To a certain degree you can even specify the resolution.
I wrote a program in VB.NET that did what you specified, except for the screen size issue.
I embedded a web control(look at the very bottom of all controls) onto my form, and tweaked it's settings(Hide scroll). I used a timer to wait on dynamic content, and then I used "copyFromScreen" to get the image.
My program had dynamic dimensions(settable via command line). I found that if I made my program larger than the screen, the image would just return black pixels for the off screen area. I did not research farther since my job was complete at that time.
Hope that gives you a good start. Sorry for any wrong wordings. I log onto windows to develop only once every couple of months.
Doing at as a screen shot is likely to get ugly. It's easy enough to capture the entire content of the page with wget, but the image means capturing the rendering.
Here's some tools that purport to do it.
You can render it on WebBrowser control and then take snapshot if page size bigger than screen size you have to scroll control take one or more snapshots and then merge all pictures :)
This is the code for creating screenshot programatically:
using System.Drawing.Imaging;
int screenWidth = Screen.GetBounds(new Point(0, 0)).Width;
int screenHeight = Screen.GetBounds(new Point(0, 0)).Height;
Bitmap bmpScreenShot = new Bitmap(screenWidth, screenHeight);
Graphics gfx = Graphics.FromImage((Image)bmpScreenShot);
gfx.CopyFromScreen(0, 0, 0, 0, new Size(screenWidth, screenHeight));
bmpScreenShot.Save("test.jpg", ImageFormat.Jpeg);
Java ScreenShots of WebSite
Combine Screens together for Final Entire WebPage Screenshot.
public static void main(String[] args) throws FileNotFoundException, IOException {
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
ChromeDriver browser = new ChromeDriver();
WebDriver driver = browser;
driver.get("https://news.google.co.in/");
driver.manage().timeouts().implicitlyWait(500, TimeUnit.SECONDS);
JavascriptExecutor jse = (JavascriptExecutor) driver;
Long clientHeight = (Long) jse.executeScript("return document.documentElement.clientHeight");
Long scrollHeight = (Long) jse.executeScript("return document.documentElement.scrollHeight");
int screens = 0, xAxis = 0, yAxis = clientHeight.intValue();
String screenNames = "D:\\Screenshots\\Yash";
for (screens = 0; ; screens++) {
if (scrollHeight.intValue() - xAxis < clientHeight) {
File crop = new File(screenNames + screens+".jpg");
FileUtils.copyFile(browser.getScreenshotAs(OutputType.FILE), crop);
BufferedImage image = ImageIO.read(new FileInputStream(crop));
int y_Axixs = scrollHeight.intValue() - xAxis;
BufferedImage croppedImage = image.getSubimage(0, image.getHeight()-y_Axixs, image.getWidth(), y_Axixs);
ImageIO.write(croppedImage, "jpg", crop);
break;
}
FileUtils.copyFile(browser.getScreenshotAs(OutputType.FILE), new File(screenNames + screens+".jpg"));
jse.executeScript("window.scrollBy("+ xAxis +", "+yAxis+")");
jse.executeScript("var elems = window.document.getElementsByTagName('*');"
+ " for(i = 0; i < elems.length; i++) { "
+ " var elemStyle = window.getComputedStyle(elems[i], null);"
+ " if(elemStyle.getPropertyValue('position') == 'fixed' && elems[i].innerHTML.length != 0 ){"
+ " elems[i].parentNode.removeChild(elems[i]); "
+ "}}"); // Sticky Content Removes
xAxis += yAxis;
}
driver.quit();
}