Monday, January 31, 2011

Web page to access clipboard exception with Watin

I have been working on a solution to get the clipboard working with Watin automated program. because security exception is really annoying!

here is goes,

class Program
{
[STAThread]
static void Main(string[] args) {


SecurityAlertDialogHandler securityAlertDialogHandlerMock = new SecurityAlertDialogHandler();

using (IE ie = new IENoWaitForComplete("url goes here")) {

ie.AddDialogHandler(securityAlertDialogHandlerMock);

//GetPicture(ie.Images[0], ie);
ie.WaitForComplete();

IEElement banner = ieImages[0].NativeElement as IEElement;

IHTMLElement bannerHtmlElem = banner.AsHtmlElement;
IEElement bodyNative = ie.Body.NativeElement as IEElement;
mshtml.IHTMLElement2 bodyHtmlElem = (mshtml.IHTMLElement2)bodyNative.AsHtmlElement;
mshtml.IHTMLControlRange controlRange = (mshtml.IHTMLControlRange)bodyHtmlElem.createControlRange();

controlRange.add((mshtml.IHTMLControlElement)bannerHtmlElem);
controlRange.execCommand("Copy", false, System.Reflection.Missing.Value);
controlRange.remove(0);

if (Clipboard.GetDataObject() != null) {
IDataObject data = Clipboard.GetDataObject();
if (data.GetDataPresent(DataFormats.Bitmap)) {
System.Drawing.Image image = (System.Drawing.Image)data.GetData(DataFormats.Bitmap, true);
// do something here
}
}
}
}

}

class IENoWaitForComplete : IE
{
public IENoWaitForComplete(string url) : base(url) { }

public override void WaitForComplete(int timeOutPeriod) {
// Skip Wait logic
}
}

class SecurityAlertDialogHandler : BaseDialogHandler
{
private bool _hasHandledSecurityAlertDialog;

public bool HasHandledSecurityAlertDialog {
get { return _hasHandledSecurityAlertDialog; }
}

public override bool HandleDialog(Window window) {
new WinButton(1, window.Hwnd).Click();
return true;
}

public override bool CanHandleDialog(Window window) {
return window.StyleInHex == "94C808CC";
}

}

No comments: