/// <summary> /// This method creates a new form with a webbrowser of correct size on it, /// to make a fullsize website screenhot. /// </summary> /// <param name="navigatingArgs">The <see cref="WebBrowserNavigatingEventArgs"/> instance containing the event data, /// especially the url.</param> /// <param name="filename">The filename to save the screenshot to.</param> public static void DoScreenshot(WebBrowserNavigatingEventArgs navigatingArgs, string filename) { newTargetUrl = navigatingArgs.Url; newScreenshotFilename = filename; var tempBrowser = new WebBrowser(); var dummyForm = new Form { ClientSize = new Size(1, 1), FormBorderStyle = FormBorderStyle.None }; dummyForm.ShowInTaskbar = false; dummyForm.Controls.Add(tempBrowser); dummyForm.Show(); tempBrowser.ScrollBarsEnabled = true; tempBrowser.ScriptErrorsSuppressed = true; tempBrowser.DocumentCompleted += WebBrowserDocumentCompleted; if (navigatingArgs.TargetFrameName != string.Empty) { tempBrowser.Navigate(navigatingArgs.Url, navigatingArgs.TargetFrameName); } else { tempBrowser.Navigate(newTargetUrl); } while (tempBrowser.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); } tempBrowser.Dispose(); }
static void Main() { for (int i = 0; i != Screen.AllScreens.Length; i++) { Form frm = new Form(); WebBrowser brs = new WebBrowser(); brs.Dock = DockStyle.Fill; brs.ScrollBarsEnabled = false; if (Screen.AllScreens[i].Primary) brs.Navigate(new Uri("http://www.cyberspace.org/~jhl")); else brs.Navigate(new Uri("http://www.c-faq.com")); frm.Controls.Add(brs); frm.FormBorderStyle = FormBorderStyle.None; frm.Show(); frm.DesktopBounds = Screen.AllScreens[i].Bounds; /*Compile this console project as Windows Application at: Project/... Properties/Application/Output type: Windows Application, this hides the console window. Override FormClosed event triggered by keystroke ALT+F4 and exit the application at the close of the last form.*/ frm.FormClosed += delegate(object obj, FormClosedEventArgs args) { if (Application.OpenForms.Count == 0) Application.Exit(); }; } Application.Run(); }
/// <summary> /// This is the crucial auto submission method used to primarily handle the bot's auto submission work /// </summary> /// <param name="browser">WebBrowser to operate on</param> /// <param name="currentlySolving">Label to show the currently solving problem's name</param> /// <param name="linkList">List of problem links to solve</param> /// <param name="awaitTime">Awaiting time after each successful submission</param> /// <returns>Bool value addressing the success of the method</returns> public async static Task<bool> AutoSubmission(WebBrowser browser, Label currentlySolving, List<string> linkList, int awaitTime) { while(linkList.Any()) { try { Random rng = new Random(); var falseSubmission = rng.Next(3); // Total false submissions for each problem // Take out a link and remove it from the list afterwards var indexToRemove = rng.Next(linkList.Count); var link = linkList[indexToRemove]; linkList.RemoveAt(indexToRemove); string solutionListPageHtml; using (var client = new WebClient()) { // Extract solution list page's html and update currently solving label's text solutionListPageHtml = await client.DownloadStringTaskAsync( StringManupulation.LinkToSolutions(link.Replace("\r", string.Empty))); currentlySolving.Text = Regex.Match(client.DownloadString(link), @"(?<=<title>)(.*)(?= \| CodeChef</title>)") .ToString(); } for (int count = 1; count <= falseSubmission; count++) { // False submissions browser.Navigate(StringManupulation.LinkToSubmission(link)); await Submit(browser, StringManupulation.FakeSourceCodeGenerator()); } // Navigate to submission page and finally submit the correct solution browser.Navigate(StringManupulation.LinkToSubmission(link)); await Submit(browser, StringManupulation.ExtractedSolution(solutionListPageHtml)); } catch (Exception) { // ignored } finally { // Wait for awaitTime before jumping for the next submission await Task.Delay(awaitTime); } } return true; }
public IeWebMedia(RegionOptions options) : base(options.width, options.height, options.top, options.left) { // Collect some options from the Region Options passed in // and store them in member variables. _options = options; // Check to see if the mode option is present. string modeId = options.Dictionary.Get("modeid"); bool nativeOpen = modeId != string.Empty && modeId == "1"; if (nativeOpen) { // If we are modeid == 1, then just open the webpage without adjusting the file path _filePath = Uri.UnescapeDataString(options.uri).Replace('+', ' '); } else { // Set the file path _filePath = ApplicationSettings.Default.LibraryPath + @"\" + _options.mediaid + ".htm"; } // Create the web view we will use _webBrowser = new WebBrowser(); _webBrowser.DocumentCompleted += _webBrowser_DocumentCompleted; _webBrowser.Size = Size; _webBrowser.ScrollBarsEnabled = false; _webBrowser.ScriptErrorsSuppressed = true; _webBrowser.Visible = false; if (nativeOpen) { // Nativate directly _webBrowser.Navigate(_filePath); } else { // Check to see if the HTML is ready for us. if (HtmlReady()) { // Write to temporary file ReadControlMeta(); // Navigate to temp file _webBrowser.Navigate(_filePath); } else { RefreshFromXmds(); } } Controls.Add(_webBrowser); // Show the control Show(); }
void IAutoWeb.Next(WebBrowser webBrowser1) { Uri url = webBrowser1.Url; // Fix bug: Why sometimes it's null? if(url == null) { return; } Console.Out.WriteLine("Next>>"); Console.Out.WriteLine(url); if (url.ToString().StartsWith(URL_LOGIN)) { this.LoginSupportedByWangWang(webBrowser1.Document); } else if (url.ToString().StartsWith(URL_ASSET)) { MoneyDatabaseUpdater dbUpdater = new MoneyDatabaseUpdater(); if (this._isTotalUpdated == false) { this._isTotalUpdated = this.RetrieveTotal(webBrowser1.Document, dbUpdater); } if (this.RetrieveDaily(webBrowser1.Document, dbUpdater)) { if (!this.ClickNextTab(webBrowser1.Document)) { webBrowser1.Navigate(URL_MIAO); } } } else if (url.ToString().StartsWith(URL_MIAO)) { if (this.GetMaoquan(webBrowser1.Document)) { webBrowser1.Navigate(URL_ETAO); } } else if (url.ToString().StartsWith(URL_ETAO)) { if (this.SignETao(webBrowser1.Document)) { this._completed = true; } } else { } }
//searches for the given url //bool isNew tells the function if the search is new or a previous search public void search(String s) { if (String.IsNullOrEmpty(s)) { return; } if (s.Equals("about:blank")) { return; } if (!s.StartsWith("http://") && !s.StartsWith("https://")) { s = "http://" + s; } try { b.Navigate(new Uri(s)); } catch (System.UriFormatException) { return; } history.Add(s); }
private void Window_Initialized(object sender, EventArgs e) { try { var tokenCachePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "droptoken"); var secretCachePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "dropsecret"); if (File.Exists(tokenCachePath) && File.Exists(secretCachePath)) { var cachedUserToken = File.ReadAllText(tokenCachePath); var cachedUserSecret = File.ReadAllText(secretCachePath); _client = new DropNetClient(appKey, appSecret, cachedUserToken, cachedUserSecret); } else { _client = new DropNetClient(appKey, appSecret); var userToken = _client.GetToken(); var tokenUrl = _client.BuildAuthorizeUrl("http://localhost:8000/token"); browser1.DocumentCompleted += Browser1OnDocumentCompleted; browser1.Navigated += Browser1OnNavigated; browser1.ScriptErrorsSuppressed = true; browser1.Navigate(new Uri(tokenUrl)); } } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } }
public override void Initialize() { XmlDocument docInitString = new XmlDocument(); docInitString.LoadXml(_initString); XmlNode nodePortalUrl = docInitString.SelectSingleNode("initstring/CitrixIntegration/portalurl"); if (nodePortalUrl == null || String.IsNullOrEmpty(nodePortalUrl.InnerText)) { // connect using a configured ICA file tInitializeDelay = new System.Threading.Timer(new TimerCallback(InitializeDelay), null, TimeSpan.FromSeconds(10), TimeSpan.Zero); } else { XmlNode nodeAutoSelect = docInitString.SelectSingleNode("initstring/CitrixIntegration/autoselecturl"); if (nodeAutoSelect != null) { autoSelect = nodeAutoSelect.InnerText; } // connect using the Citrix web portal ICAClient.Visible = false; webBrowser1 = new System.Windows.Forms.WebBrowser(); this.Controls.Add(webBrowser1); webBrowser1.Dock = System.Windows.Forms.DockStyle.Fill; webBrowser1.Visible = true; webBrowser1.Navigating += new System.Windows.Forms.WebBrowserNavigatingEventHandler(webBrowser1_Navigating); webBrowser1.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted); webBrowser1.Navigate(nodePortalUrl.InnerText); InitializeEx(); } }
private void BrowserWindow_Load(object sender, EventArgs e) { try { DeleteBrowserCache.Execute(); _webBrowser = new WebBrowser(); _webBrowser.AllowNavigation = true; _webBrowser.Navigated += _webBrowser_Navigated; _webBrowser.Navigate(_startUrl); _webBrowser.Width = 600; _webBrowser.Height = 600; _webBrowser.ScriptErrorsSuppressed = true; Controls.Add(_webBrowser); } catch (ThreadStateException) { throw new ThreadStateException("Make sure you added the [STAThread] attribute to the main function."); } catch (Exception) { throw; } }
private void loginNico() { try { toolStripStatusLabel2.Text = "Giriş Yapılıyor.."; wb = new WebBrowser(); wb.ScriptErrorsSuppressed = true; wb.Navigate("http://www.nicovideo.jp/login"); while (wb.ReadyState != WebBrowserReadyState.Complete) Application.DoEvents(); wb.Document.GetElementById("mail").InnerText = "*****@*****.**"; wb.Document.GetElementById("password").InnerText = "1725839"; foreach (HtmlElement el in wb.Document.GetElementsByTagName("input")) { if (el.GetAttribute("type").Equals("submit")) { el.InvokeMember("click"); break; } } } catch{ toolStripStatusLabel2.Text = "Giriş Başarısız.."; } toolStripStatusLabel2.Text = "Giriş Başarılı.."; button2.Enabled = true; }
public static void GetHTML(string url, Func <string, object> successFunc, Func <string, object> errorFunc) { System.Windows.Forms.WebBrowser wb = new System.Windows.Forms.WebBrowser(); Timer timer = new Timer(); timer.Interval = 1000; int i = 0; string html = ""; timer.Tick += (o, a) => { html = wb.DocumentText; if (html.ToLower().Contains("</html>")) { successFunc(html); timer.Enabled = false; } else if (i++ > 100) { errorFunc(html); timer.Enabled = false; } }; wb.Navigated += (s, e) => timer.Enabled = true; wb.Navigate(url); }
public static DialogResult DoOAuth() { Size size = _dropboxAuthFormSize; using (var dialog = new Form()) { WebBrowser browesr = new WebBrowser() { Dock = DockStyle.Fill }; string authUrl = Client.BuildAuthorizeUrl(); // Event handler browesr.Navigated += (s, ex) => { var url = ex.Url.ToString(); if (url.Equals(_callbackURL)) { dialog.DialogResult = DialogResult.OK; } else if (url.Equals(_cancelCallbackURL)) { dialog.DialogResult = DialogResult.Cancel; } }; browesr.Navigate(authUrl); dialog.Size = size; dialog.Controls.Add(browesr); dialog.StartPosition = FormStartPosition.CenterParent; return dialog.ShowDialog(); } }
/// <summary> /// basic constructor /// </summary> /// <param name="_GeWebBrowser"></param> public DrawMap(WebBrowser GeWebBrowser) { if (CheckInternetConnect.IsConnectedToInternet() == true) { this.external = new External(); this.GE = new GoogleEarth(); //--connect event handler--// this.external.PluginReady += this.GE.external_PluginReady; //this.external.KmlMouseClickEvent += this.GE.external_MouseClick; GeWebBrowser.ObjectForScripting = this.external; //--insert your localhost.html address below mathod--// GeWebBrowser.Navigate( "C:\\Projectdata\\Google\\PlugIn.htm"); this.data = new List<gpsData>(); this.data.Clear(); this.IsInitialize = false; this.readCnt = 0; //--debug for whether selected or not selected--// GE.StartGoogleEarth = true; this.debugMsg = "Start Google Earth"; } else { this.debugMsg = "Network is not connected"; } }
/// <summary> /// The open. /// </summary> /// <param name="url"> /// The url. /// </param> public static void Open(string url) { try { Process.Start(url); } catch { try { // How about IE? Process.Start("iexplore", url); } catch { var browserForm = new SmartForm { Text = "Popup Browser", Icon = Resources.SkyDeanBlackIcon, WindowState = FormWindowState.Maximized }; var browser = new WebBrowser { Dock = DockStyle.Fill }; browser.Navigate(url); browserForm.Controls.Add(browser); browserForm.Show(); } } }
public void BitmapThreadWorker(object url) { try { DateTime started = DateTime.Now; WebBrowser browser = new WebBrowser(); browser.ScrollBarsEnabled = false; browser.ClientSize = new Size(800, 600); browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(browser_DocumentCompleted); browser.Navigate((string)url); while (bmp == null) { Thread.Sleep(1000); Application.DoEvents(); TimeSpan elapsed = DateTime.Now.Subtract(started); if (elapsed.TotalMilliseconds > s_RequestTimeout / 2) { browser.Dispose(); mre.Set(); break; } } } catch { mre.Set(); } }
private static void runBrowserThread(string url) { try { var th = new Thread(() => { Console.WriteLine(">>>Запуск процесса парсинга"); var br = new WebBrowser(); br.DocumentCompleted += browser_DocumentCompleted; br.ScriptErrorsSuppressed = true; br.Navigate(url); Application.Run(); }); th.SetApartmentState(ApartmentState.STA); th.Start(); } catch (Exception ex) { Console.WriteLine(">>>Ошибка:" + ex.ToString()); } finally { Console.WriteLine(">>>Парсинг"); } }
private static Image Capture(string url, Size size) { Image result = new Bitmap(size.Width, size.Height); var thread = new Thread(() => { using (var browser = new WebBrowser()) { browser.ScrollBarsEnabled = false; browser.AllowNavigation = true; browser.Navigate(url); browser.Width = size.Width; browser.Height = size.Height; browser.ScriptErrorsSuppressed = true; browser.DocumentCompleted += (sender,args) => DocumentCompleted(sender, args, ref result); while (browser.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); } } }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); return result; }
public HttpResponseMessage Post(EmailModel value) { var waiter = new ManualResetEvent(true); var staThread = new Thread(() => { var browser = new WebBrowser(); browser.DocumentCompleted += (sender, e) => { waiter.Set(); // Signal the web service thread we're done. Wtf = "fuckkkkkkkkkk"; }; browser.Navigate("http://www.google.com"); }); staThread.SetApartmentState(ApartmentState.STA); staThread.Start(); var timeout = TimeSpan.FromSeconds(30); waiter.WaitOne(timeout); // Wait for the STA thread to finish. var client = new MailgunClient("app15162.mailgun.org", "key-8-br6rzagyq2r4593n-iqmx-lrlkf902"); var message = new MailMessage(value.From, value.To, value.Title, value.Content); client.SendMail(message); return Request.CreateResponse(HttpStatusCode.OK, value); }
////////////////////////////////////////////////////////////////////////// // Web Document 操作 処理関数 /// <summary> /// id = fileurl の filePathを取得する /// </summary> /// <param name="url"></param> /// <returns></returns> public static String GetPathByID(String url) { // create a hidden web browser, which will navigate to the page System.Windows.Forms.WebBrowser web = new System.Windows.Forms.WebBrowser(); web.ScrollBarsEnabled = false; // we don't want scrollbars on our image web.ScriptErrorsSuppressed = true; // don't let any errors shine through web.Navigate(url); // let's load up that page! // wait until the page is fully loaded while (web.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete) { System.Windows.Forms.Application.DoEvents(); } //System.Threading.Thread.Sleep(1500); // allow time for page scripts to update // the appearance of the page HtmlWindow currentWindow = web.Document.Window; String fileurl = ""; if (web.Document.GetElementById("fileurl") != null) { fileurl = web.Document.GetElementById("fileurl").InnerText; fileurl = Url2Path(fileurl); } web.Dispose(); return(fileurl); }
private static void AuthorizeClient(AppServiceClient appServiceClient) { Form frm = new Form(); frm.Width = 640; frm.Height = 480; WebBrowser browser = new WebBrowser(); browser.Dock = DockStyle.Fill; browser.DocumentCompleted += (sender, e) => { if (e.Url.AbsoluteUri.IndexOf(URL_TOKEN) > -1) { var encodedJson = e.Url.AbsoluteUri.Substring(e.Url.AbsoluteUri.IndexOf(URL_TOKEN) + URL_TOKEN.Length); var decodedJson = Uri.UnescapeDataString(encodedJson); var result = JsonConvert.DeserializeObject<dynamic>(decodedJson); string userId = result.user.userId; string userToken = result.authenticationToken; appServiceClient.SetCurrentUser(userId, userToken); frm.Close(); } }; browser.Navigate(string.Format(@"{0}login/twitter", GW_URL)); frm.Controls.Add(browser); frm.ShowDialog(); }
public Task<SurveyNewsFeed> GetFeedAsync(string feedUrl) { // We can't use a simple WebRequest, because that doesn't have access // to the browser's session cookies. Cookies are used to remember // which survey/news item the user has submitted/accepted. The server // checks the cookies and returns the survey/news urls that are // currently available (availability is determined via the survey/news // item start and end date). var tcs = new TaskCompletionSource<SurveyNewsFeed>(); try { var thread = new Thread(() => { var browser = new WebBrowser(); browser.DocumentCompleted += (sender, e) => { try { if (browser.Url == e.Url) { SurveyNewsFeed feed = ParseFeed(browser); tcs.SetResult(feed); Application.ExitThread(); } } catch (Exception ex2) { tcs.SetException(ex2); } }; browser.Navigate(new Uri(feedUrl)); Application.Run(); }); thread.Name = "SurveyNewsFeedClient"; thread.SetApartmentState(ApartmentState.STA); thread.Start(); } catch (Exception ex1) { tcs.SetException(ex1); } return tcs.Task; }
/// <summary> /// A method to capture a webpage as a System.Drawing.Bitmap /// </summary> /// <param name="URL">The URL of the webpage to capture</param> /// <returns>A System.Drawing.Bitmap of the entire page</returns> public static System.Drawing.Bitmap CaptureWebPage(string URL) { // create a hidden web browser, which will navigate to the page System.Windows.Forms.WebBrowser web = new System.Windows.Forms.WebBrowser(); web.ScrollBarsEnabled = false; // we don't want scrollbars on our image web.ScriptErrorsSuppressed = true; // don't let any errors shine through web.Navigate(URL); // let's load up that page! // wait until the page is fully loaded while (web.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete) { System.Windows.Forms.Application.DoEvents(); } System.Threading.Thread.Sleep(1500); // allow time for page scripts to update // the appearance of the page // set the size of our web browser to be the same size as the page int width = web.Document.Body.ScrollRectangle.Width; int height = web.Document.Body.ScrollRectangle.Height; web.Width = width; web.Height = height; // a bitmap that we will draw to System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(width, height); // draw the web browser to the bitmap web.DrawToBitmap(bmp, new System.Drawing.Rectangle(0, 0, width, height)); return(bmp); // return the bitmap for processing }
public void Start() { BrowserThread = new Thread(() => { Browser = new WebBrowser(); Browser.Width = Ballz.The().GraphicsDevice.Viewport.Width; Browser.Height = Ballz.The().GraphicsDevice.Viewport.Height; Browser.ScrollBarsEnabled = false; //Browser.IsWebBrowserContextMenuEnabled = false; LatestBitmap = new Bitmap(Browser.Width, Browser.Height); Browser.Validated += (s, e) => { lock (this) { Browser.DrawToBitmap(LatestBitmap, new Rectangle(0, 0, Browser.Width, Browser.Height)); } }; Browser.DocumentCompleted += (s, e) => { lock (this) { Browser.DrawToBitmap(LatestBitmap, new Rectangle(0, 0, Browser.Width, Browser.Height)); } }; Browser.Navigate("file://C:/Users/Lukas/Documents/gui.html"); var context = new ApplicationContext(); Application.Run(); }); BrowserThread.SetApartmentState(ApartmentState.STA); BrowserThread.Start(); }
private void webBrowser_NewWindow(object sender, CancelEventArgs e) { AfreshMonOutTime(); e.Cancel = true; web.Navigate(this.web.StatusText); }
private void InternalUpdateURL() { if (_uRL != String.Empty) { try { _webBrowser.Navigate(_uRL); return; } catch { // Do nothing } } _webBrowser.Navigate("about:blank"); }
public static Bitmap GetScreenshot(Uri uri, int width, int height) { Bitmap bitmap; using (var webBrowser = new WebBrowser()) { webBrowser.ScrollBarsEnabled = false; webBrowser.ScriptErrorsSuppressed = true; webBrowser.Navigate(uri); while (webBrowser.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); } webBrowser.Width = width > 0 ? width : webBrowser.Document.Body.ScrollRectangle.Width; webBrowser.Height = height > 0 ? height : webBrowser.Document.Body.ScrollRectangle.Height; if (webBrowser.Height <= 0) webBrowser.Height = 768; bitmap = new Bitmap(webBrowser.Width, webBrowser.Height); webBrowser.DrawToBitmap(bitmap, new Rectangle(0, 0, webBrowser.Width, webBrowser.Height)); } return bitmap; }
public static void showFunctionBlocksInWebBrower(List<ControlFlowGraphBasicBlock> lcfgBasicBlocks, WebBrowser webBrowser) { if (lcfgBasicBlocks != null && lcfgBasicBlocks.Count > 0) { var blockXml = new StringBuilder(); foreach (ControlFlowGraphBasicBlock basicBlock in lcfgBasicBlocks) { //var tempFile = DI.o2CorLibConfig.TempFileNameInTempDirectory; string xmlContentOfBasicBlock = Serialize.createSerializedXmlStringFromObject(basicBlock,null); if (xmlContentOfBasicBlock != "") { blockXml.AppendLine("<BASICBLOCK>" + xmlContentOfBasicBlock + "</BASICBLOCK>"); } } // Hack to create Xml Doc (replace with proper viewer) var xmlDocument = new XmlDocument(); //var root = xmlDocument.DocumentElement; XmlElement childNode = xmlDocument.CreateElement("Content"); childNode.InnerXml = blockXml.ToString().Replace("<?xml version=\"1.0\"?>", ""); xmlDocument.AppendChild(childNode); string tempXmlFile = DI.config.TempFileNameInTempDirectory + ".xml"; xmlDocument.Save(tempXmlFile); webBrowser.Navigate(tempXmlFile); } }
//TODO enable private static void Nailer(string screenNailerId, string RefId, string url) { ReferenceId = RefId; ScreenNailerId = screenNailerId; WriteLog("In Nailer screenNailerId " + screenNailerId + " RefId " + RefId + " url" + url); int width = 1280; int height = 768; using (WebBrowser browser = new WebBrowser()) { browser.Width = width; browser.Height = height; browser.ScrollBarsEnabled = false; // This will be called when the page finishes loading browser.DocumentCompleted += Program.OnDocumentCompleted; browser.Navigate(url); // This prevents the application from exiting until // Application.Exit is called Application.Run(); } }
public Bitmap GenerateScreenshot(string url, int width, int height) { WebBrowser wb = new WebBrowser(); wb.NewWindow += wb_NewWindow; wb.ScrollBarsEnabled = false; wb.ScriptErrorsSuppressed = true; wb.Navigate(url); while (wb.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); } Thread.Sleep(int.Parse(ConfigurationSettings.AppSettings["WaitForLoadWebSite"].ToString().Trim())); wb.Width = width; wb.Height = height; if (width == -1) { wb.Width = wb.Document.Body.ScrollRectangle.Width; } if (height == -1) { wb.Height = wb.Document.Body.ScrollRectangle.Height; } Bitmap bitmap = new Bitmap(wb.Width, wb.Height); wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height)); wb.Dispose(); return bitmap; }
/// <summary> /// Returns a SharePoint on-premises / SharePoint Online ClientContext object. Requires claims based authentication with FedAuth cookie. /// </summary> /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param> /// <param name="icon">Optional icon to use for the popup form</param> /// <returns>ClientContext to be used by CSOM code</returns> public ClientContext GetWebLoginClientContext(string siteUrl, System.Drawing.Icon icon = null) { var cookies = new CookieContainer(); var siteUri = new Uri(siteUrl); var thread = new Thread(() => { var form = new System.Windows.Forms.Form(); if (icon != null) { form.Icon = icon; } var browser = new System.Windows.Forms.WebBrowser { ScriptErrorsSuppressed = true, Dock = DockStyle.Fill }; form.SuspendLayout(); form.Width = 900; form.Height = 500; form.Text = $"Log in to {siteUrl}"; form.Controls.Add(browser); form.ResumeLayout(false); browser.Navigate(siteUri); browser.Navigated += (sender, args) => { if (siteUri.Host.Equals(args.Url.Host)) { var cookieString = CookieReader.GetCookie(siteUrl).Replace("; ", ",").Replace(";", ","); if (Regex.IsMatch(cookieString, "FedAuth", RegexOptions.IgnoreCase)) { var _cookies = cookieString.Split(',').Where(c => c.StartsWith("FedAuth", StringComparison.InvariantCultureIgnoreCase) || c.StartsWith("rtFa", StringComparison.InvariantCultureIgnoreCase)); cookies.SetCookies(siteUri, string.Join(",", _cookies)); form.Close(); } } }; form.Focus(); form.ShowDialog(); browser.Dispose(); }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); if (cookies.Count > 0) { var ctx = new ClientContext(siteUrl); ctx.ExecutingWebRequest += (sender, e) => e.WebRequestExecutor.WebRequest.CookieContainer = cookies; return(ctx); } return(null); }
private void Browser_NewWindow(object sender, CancelEventArgs e) { //获取触发tempBrowser_NewWindow事件的浏览器 WebBrowser myBrowser = (WebBrowser)sender; //获取触发tempBrowser_NewWindow事件的浏览器所在TabPage XtraTabPage mypage = (XtraTabPage)myBrowser.Parent; //通过StatusText属性获得新的url string NewURL = ((WebBrowser)sender).StatusText; //生成新的一页 XtraTabPage TabPageTemp = new XtraTabPage(); //生成新的tempBrowser WebBrowser tempBrowser = new WebBrowser(); //临时浏览器定向到新的url tempBrowser.Navigate(NewURL); tempBrowser.Dock = DockStyle.Fill; //为临时浏览器关联NewWindow等事件 tempBrowser.NewWindow += new CancelEventHandler(Browser_NewWindow); tempBrowser.Navigated += new WebBrowserNavigatedEventHandler(Browser_Navigated); tempBrowser.ProgressChanged += new WebBrowserProgressChangedEventHandler(Browser_ProgressChanged); tempBrowser.StatusTextChanged += new EventHandler(Browser_StatusTextChanged); tempBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(Browser_DocumentCompleted); //将临时浏览器添加到临时TabPage中 TabPageTemp.Controls.Add(tempBrowser); //将临时TabPage添加到主窗体中 this.tctlControl.TabPages.Add(TabPageTemp); TabPageTemp.Text = "加载中"; //使外部无法捕获此事件 e.Cancel = true; DisbaledRight(tempBrowser); }
static void Main(string[] args) { System.Console.WriteLine("Create your own web history images."); System.Console.WriteLine("Type the URL (with http://..."); string url = System.Console.ReadLine(); System.Console.WriteLine(@"Save to location (e.g. C:\Images\)"); string path = System.Console.ReadLine(); IArchiveService service = new WebArchiveService(); Website result = service.Load(url); System.Console.WriteLine("WebArchive Sites found: " + result.ArchiveWebsites.Count); WebBrowser wb = new WebBrowser(); int i = 0; foreach (ArchiveWebsite site in result.ArchiveWebsites) { i++; System.Console.WriteLine("Save image (Date " + site.Date.ToShortDateString() + ") number: " + i.ToString()); wb.ScrollBarsEnabled = false; wb.ScriptErrorsSuppressed = true; wb.Navigate(site.ArchiveUrl); while (wb.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); } wb.Width = wb.Document.Body.ScrollRectangle.Width; wb.Height = wb.Document.Body.ScrollRectangle.Height; Bitmap bitmap = new Bitmap(wb.Width, wb.Height); wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height)); bitmap.Save(path + site.Date.Year.ToString() + "_" + site.Date.Month.ToString() + "_" + site.Date.Day.ToString() + ".bmp"); } wb.Dispose(); System.Console.WriteLine(result.Url); }
internal override void CreateImage(string imagePath) { Thread thread = new Thread(delegate() { using (WebBrowser browser = new WebBrowser()) { browser.ScrollBarsEnabled = false; browser.AllowNavigation = true; string tempPath = imagePath + ".html"; File.WriteAllText(tempPath, this.Html); browser.Navigate(tempPath); browser.ScriptErrorsSuppressed = true; //browser.Width = 1024; //browser.Height = 19999; browser.Tag = imagePath; browser.DocumentCompleted += DocumentCompleted; while (browser.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); } } }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); base.CreateImage(imagePath); }
public void preview(WebBrowser webBrowser, List<Step> tuts) { webBrowser.Navigate("about:blank"); HtmlDocument doc = webBrowser.Document; doc.OpenNew(true); doc.Write(render(tuts)); }
public static void SetHtmlContent(this System.Windows.Forms.WebBrowser webBrowser, string html, string baseUrl) { webBrowser.Navigate("about:blank"); var browser = (IWebBrowser2)webBrowser.ActiveXInstance; var result = CreateStreamOnHGlobal(Marshal.StringToHGlobalAuto(html), true, out IStream stream); if ((result != 0) || (stream == null)) { return; } var persistentMoniker = browser.Document as IPersistMoniker; if (persistentMoniker == null) { return; } IBindCtx bindContext = null; CreateBindCtx((uint)0, out bindContext); if (bindContext == null) { return; } var loader = new Moniker(baseUrl, html); persistentMoniker.Load(1, loader, bindContext, (uint)0); stream = null; }
internal static Image RequestSnapshot(Uri url) { Image result = null; using (var completed = new AutoResetEvent(false)) using (var browser = new WebBrowser()) { browser.ScrollBarsEnabled = false; browser.DocumentCompleted += delegate { result = ExtractSnapshot(browser); completed.Set(); }; browser.Navigate(url); //completed.WaitOne(); while (result == null) { Thread.Sleep(0); Application.DoEvents(); } } return result; }
//Method "Browse()" provided by assignment description private String Browse() { // Can't find System.Windows.Controls.WebBrowser, which might be nice. // See http://stackoverflow.com/questions/8645926/how-to-create-and-use-webbrowser-in-background-thread WebBrowser myWebBrowser = null; String innerHTML = ""; txtTitle.Text = "???"; txtValue.Text = "???"; Thread thread = new Thread(delegate() { int elapsedTime; DateTime startTime = new DateTime(), endTime = new DateTime(); startTime = DateTime.Now; System.Windows.Forms.HtmlElement htmlElement = null; //WebBrowser foo = new System.Net.HttpWebRequest(); // deprecated. Seems to work for Desktop Apps and .Net Framework 2.0 // This causes major crashing of the web server //foo.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(DocumentComplete); myWebBrowser = new System.Windows.Forms.WebBrowser(); // Must be instantiated inside the Thread myWebBrowser.AllowNavigation = true; myWebBrowser.Navigate(txtURL.Text, false); while (myWebBrowser.ReadyState != WebBrowserReadyState.Complete) //while (foo.ReadyState != WebBrowserReadyState.Interactive) // We don't care if the graphics are loaded //while (foo.IsBusy == true) { txtValue.Text = myWebBrowser.ReadyState.ToString(); System.Windows.Forms.Application.DoEvents(); endTime = DateTime.Now; elapsedTime = (endTime - startTime).Seconds; if (elapsedTime > 30) { break; } } // When we get this far we have hopefully loaded the web page into the browser object try { txtTitle.Text = myWebBrowser.Document.Title; //System.Windows.Forms.HtmlElement x = foo.Document.GetElementById("yfs_l84_csco"); htmlElement = myWebBrowser.Document.Body; innerHTML = htmlElement.InnerHtml; } catch (Exception ex) { txtValue.Text += "<p> Exception: " + ex.ToString(); } }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); // We won't get here until the Thread completes. // This might be interesting: http://www.charith.gunasekara.web-sphere.co.uk/2010/09/how-to-convert-html-page-to-image-using.html return(innerHTML); }
void HandleGtkRealized(object sender, EventArgs e) { var size = new System.Drawing.Size(Widget.WidthRequest, Widget.HeightRequest); var createView = view == null; if (createView) { view = new SWF.WebBrowser(); view.ScriptErrorsSuppressed = true; view.AllowWebBrowserDrop = false; view.Size = size; } var browser_handle = view.Handle; IntPtr window_handle = (IntPtr)socket.Id; SetParent(browser_handle, window_handle); if (createView) { view.ProgressChanged += HandleProgressChanged; view.Navigating += HandleNavigating; view.Navigated += HandleNavigated; view.DocumentTitleChanged += HandleDocumentTitleChanged; view.DocumentCompleted += (s, ev) => { var inFocus = false; view.Document.Focusing += (sD, eD) => { this.SetFocus(); inFocus = true; ApplicationContext.InvokeUserCode(delegate { EventSink.OnGotFocus(); }); }; view.Document.LosingFocus += (sD, eD) => { ApplicationContext.InvokeUserCode(delegate { EventSink.OnLostFocus(); }); inFocus = false; }; view.Document.MouseDown += (sD, eD) => { var a = new ButtonEventArgs { X = eD.MousePosition.X, Y = eD.MousePosition.Y }; ApplicationContext.InvokeUserCode(delegate { EventSink.OnButtonPressed(a); }); }; }; if (url != null) { view.Navigate(url); } } else { view.Size = size; Widget.QueueResize(); } }
private void btnLogout_Click(object sender, EventArgs e) { var webBrowser = new WebBrowser(); var fb = new FacebookClient(); var logouUrl = fb.GetLogoutUrl(new { access_token = _accessToken, next = "https://www.facebook.com/connect/login_success.html" }); webBrowser.Navigate(logouUrl); btnLogout.Visible = false; }
private void loginButton_Click(object sender, EventArgs e) { status.Text = "Logging In..."; loginButton.Enabled = false; browser = new WebBrowser(); browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(browser_DocumentCompleted); browser.Navigate("http://net12.co.tv/api/post?username="******"&password=" + passwordText.Text); }
public browser() { webbrowser = new WebBrowser (); webbrowser.Dock = DockStyle.Fill; this.Controls.Add (webbrowser); webbrowser.Navigate ("http://www.google.com"); }
public void runWebPageSearch() { isStartup = true; webBrowser1 = new WebBrowser(); webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;//ADD DOCUMENT COMPLETED EVENT LISTINER webBrowser1.Navigate("http://db.systemsbiology.net/kaviar/cgi-pub/Kaviar.pl"); waitReadyState(); }
//protected override CreateParams CreateParams //{ // get // { // const int WS_EX_APPWINDOW = 0x40000; // const int WS_EX_TOOLWINDOW = 0x80; // CreateParams cp = base.CreateParams; // cp.ExStyle &= (~WS_EX_APPWINDOW); // 不显示在TaskBar // cp.ExStyle |= WS_EX_TOOLWINDOW; // 不显示在Alt-Tab // return cp; // } //} public MainWindow_Tiamo() { InitializeComponent(); InitialTray(); ShowInTaskbar = false;//不在任务栏显示 //SetWindowLong(this, WS_EX_TOOLWINDOW); this.Focusable = false; //this.IsEnabled = false;//可以固定位置 this.IsTabStop = false; //this.ResizeMode = System.Windows.ResizeMode.CanResizeWithGrip; this.Topmost = false; //this.WindowState = System.Windows.WindowState.Minimized; web.Navigate("https://www.baidu.com/s?wd=ip&ie=UTF-8"); web.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(web_DocumentCompleted); ThreadPool.UnsafeQueueUserWorkItem(new WaitCallback((object s) => { while (true) { DateTime dt = DateTime.Now; if (dt.Second == 0) { UpDateTime(dt); Thread.Sleep((60) * 1000); } else { UpDateTime(dt); Thread.Sleep(1000); } } }), null); ThreadPool.UnsafeQueueUserWorkItem(new WaitCallback((object s) => { while (true) { UpWeather(); Thread.Sleep((60) * 1000 * 5); } }), null); //label4.Content = GetWeather(); double Top = Convert.ToDouble(ConfigurationManager.AppSettings["Top"]); double Left = Convert.ToDouble(ConfigurationManager.AppSettings["Left"]); WinPosition(Top, Left); this.Deactivated += MainWindow_Tiamo_Deactivated; //this.SourceInitialized += new EventHandler(MainWindow_SourceInitialized); }
void f_browser_Navigate(string url = "") { url = "https://www.google.com.vn/"; url = "https://www.google.com/search?q=english+pronunciation"; url = "https://pronuncian.com/"; log("GO: " + url); m_brow_web.Navigate(url); }
public ChatControl(ref System.Windows.Forms.WebBrowser browser, string pageurl) { wb = browser; wb.ObjectForScripting = this; wb.Navigate(pageurl); wb.AllowNavigation = false; OpcodesProxy.registerHandler <GameChatPanel>(Opcodes.S2CChatMessageNotify, this.chatMessageCallback, (GameChatPanel)browser.Parent); }
void TsTxtAdres_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode != Keys.Enter) { return; } ToolStripTextBox send = sender as ToolStripTextBox; wb.Navigate(send.Text); }
static void Main() { var fileName = "http://google.com"; browser = new System.Windows.Forms.WebBrowser(); browser.ScriptErrorsSuppressed = true; browser.DocumentCompleted += browser_DocumentCompleted; browser.Navigate(fileName); Application.Run(); }
public bool Init(System.Windows.Forms.WebBrowser browser) { bool res = false; _browser = browser; browser.Navigate(url); return(res); }
private void SendFeedback() { String SendText = txtText.Text.Replace(Environment.NewLine, "_555_"); String Name = txtName.Text; String CeloVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(); String url = String.Format("http://www.neffware.com/downloads/celo/fback/feedback.php?user={0}&text={1}&version={2}", Name, SendText, CeloVersion); wb.DocumentCompleted += Wb_DocumentCompleted; wb.Navigate(new Uri(url)); }
private void ZautocNaHraca() { pocetZobrazeni = 0; idHrac = _form.listHracov[_form.listHracov.IndexOf(new Hrac(hladanyHrac, "", ""))].ID; // http://www.stargate-game.cz/utok.php?jakej=2&cil= stare // http://www.stargate-game.cz/utok.php?page=0&hrac_id=1224426&utok_id=5 var url = new Uri("http://www.stargate-game.cz/utok.php?page=0&hrac_id=" + idHrac + "&utok_id=5"); wbUtok.Navigate(url); while (true) { Application.DoEvents(); if (!string.IsNullOrEmpty(wbUtok.StatusText) && !wbUtok.StatusText.Contains("utok.php")) { break; } } CultureInfo elGR = CultureInfo.CreateSpecificCulture("el-GR"); wbUtok.Document.GetElementsByTagName("input").GetElementsByName("jed1")[0].SetAttribute("value", int.Parse(_pocetPechota).ToString("0,0", elGR)); //pech[0].SetAttribute("value", _pocetPechota); //var EB = wbUtok.Document.GetElementsByTagName("input").GetElementsByName("jednot5"); //EB[0].SetAttribute("value", _pocetEB); var c = wbUtok.Document.GetElementsByTagName("input"); var d = wbUtok.Document.GetElementsByTagName("input").GetElementsByName("zautocit"); d[0].InvokeMember("Click"); var vystx = 0; var vysty = 0; var fmx = wbUtok.Parent.Location.X; var fmy = wbUtok.Parent.Location.Y; var item = c[5]; var wbx = wbUtok.Location.X; var wby = wbUtok.Location.Y; vystx = item.OffsetRectangle.X; vysty = item.OffsetRectangle.Y; var x = vystx + fmx + wbx + 10; var y = vysty + fmy + wby + 40; _form.TopMost = true; var screenBounds = Screen.PrimaryScreen.Bounds; Console.WriteLine(DateTime.Now.TimeOfDay + @" Utok"); DoMouseClick(x * 65535 / screenBounds.Width, y * 65535 / screenBounds.Height); }
// 在本软件开启窗口 private void wbView_NewWindow(object sender, CancelEventArgs e) { System.Windows.Forms.WebBrowser wbView = (System.Windows.Forms.WebBrowser)sender; e.Cancel = true; string nativeUrl = wbView.StatusText; Console.WriteLine(nativeUrl); wbView.Navigate(nativeUrl); }
public Form1() { InitializeComponent(); _server = new CassiniDevServer(); // our content is Copy Always into bin _server.StartServer(Path.Combine(Environment.CurrentDirectory, "WebContent")); _webBrowser1.Navigate(_server.NormalizeUrl("default.aspx")); }
protected void Navigate(Uri to, bool erase_forward) { // Clear the forward history if (erase_forward && UrlHistory.Position >= 0) { m_url_history.RemoveToEnd(UrlHistory.Position); } // Navigate to the given URL m_wb.Navigate(to); }
private async Task WebCookies(string url, CookieDictionary cookie) { await Task.Run(() => { var i = 0; foreach (var pair in cookie.Select(t => cookie.ElementAt(i++))) { InternetSetCookie(url, pair.Key, pair.Value); } Web.Navigate(url); }); }
public void Run(string Uri, Action <string> imgPathName, int width) { _imgPathName = imgPathName; _width = width; var browser = new System.Windows.Forms.WebBrowser(); browser.DocumentCompleted += OnDocumentCompleted; browser.Navigate(Uri); }
public void load_map(System.Windows.Forms.WebBrowser webBrowser) { if (this.webBrowser == null) { this.webBrowser = webBrowser; } string url = Application.StartupPath + "\\baidumap_grid.html"; webBrowser.ScriptErrorsSuppressed = true; webBrowser.Navigate(url); webBrowser.IsWebBrowserContextMenuEnabled = false; }
public StartForm() : base() { Load += StartForm_Load; //This call is required by the Windows Form Designer. InitializeComponent(); HtmlViewer1.Navigate("about:blank"); //HtmlViewer1.Document.OpenNew(false); //TODO: re-implement silent //HtmlViewer1.Silent = True //Add any initialization after the InitializeComponent() call }
private void Button_Click(object sender, RoutedEventArgs e) { try { DateTime dt = Convert.ToDateTime(dataOd.Text); } catch (FormatException) { dataOd.Text = DateTime.Today.Date.ToString(); } try { Convert.ToDateTime(dataDo.Text); } catch (FormatException) { dataDo.Text = DateTime.Today.Date.ToString(); } try { FolderBrowserDialog folderBrowser = new FolderBrowserDialog(); if (folderBrowser.ShowDialog() == System.Windows.Forms.DialogResult.OK) { sciezkaZapisu = folderBrowser.SelectedPath; } } catch (Exception ex) { MyMessageBox.Show("Treść błędu:\n" + ex.Message, "Błąd!", MyMessageBoxButtons.Ok); } if (string.IsNullOrWhiteSpace(sciezkaZapisu)) { MyMessageBox.Show("Nie wybrono folderu docelowego!", "Błąd", MyMessageBoxButtons.Ok); } else { webBrowser1 = new System.Windows.Forms.WebBrowser(); progressBar.Value = 0; webBrowser1.ScriptErrorsSuppressed = true; hostt.Child = webBrowser1; login = loginTextBox.Text; pass = passTextBox.Text; webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted; webBrowser1.Navigate(new Uri("https://szoi.nfz.poznan.pl/ap-mzwi/servlet/mzwiauth/flogin?")); } }
private void ScreenPop(string Url) { var url = DecodeUrlString(Url); if (!PushUrlToPolicyCenterWindow(url)) { var wb = new System.Windows.Forms.WebBrowser(); wb.Navigate(url, true); wb.Focus(); } }
private void webBrowser1_DocumentCompleted2(object sender, WebBrowserDocumentCompletedEventArgs e) { System.Windows.Forms.WebBrowser bro = sender as System.Windows.Forms.WebBrowser; if (bro.ReadyState == WebBrowserReadyState.Complete) { bro.Navigate(new Uri("https://szoi.nfz.poznan.pl/ap-mzwi/servlet/mzwiuser/komun")); bro.DocumentCompleted -= webBrowser1_DocumentCompleted2; bro.DocumentCompleted += webBrowser1_DocumentCompleted3; } }