A veces, un componente del temporizador es útil y fácil de configurar en WinForms, simplemente establezca su intervalo y luego habilítelo, luego asegúrese de que lo primero que hace en su controlador de eventos Tick es deshabilitarse.
Creo que Timer ejecuta el código en su propio hilo, por lo que puede necesitar hacer un BeginInvoke (llamado al objeto WinForm [this]) para ejecutar su Acción.
private WebBrowserDocumentCompletedEventHandler handler; //need to make it a class field for the handler below (anonymous delegates seem to capture state at point of definition, so they can't capture their own reference)
private string imageFilename;
private bool exit;
public void CaptureScreenshot(Uri address = null, string imageFilename = null, int msecDelay = 0, bool exit = false)
{
handler = (s, e) =>
{
webBrowser.DocumentCompleted -= handler; //must do first
this.imageFilename = imageFilename;
this.exit = exit;
timerScreenshot.Interval = (msecDelay > 0)? msecDelay : 1;
timerScreenshot.Enabled = true;
};
webBrowser.DocumentCompleted += handler;
Go(address); //if address == null, will use URL from UI
}
private void timerScreenshot_Tick(object sender, EventArgs e)
{
timerScreenshot.Enabled = false; //must do first
BeginInvoke((Action)(() => //Invoke at UI thread
{ //run in UI thread
BringToFront();
Bitmap bitmap = webBrowser.GetScreenshot();
if (imageFilename == null)
imageFilename = bitmap.ShowSaveFileDialog();
if (imageFilename != null)
{
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(imageFilename))); //create any parent directories needed
bitmap.Save(imageFilename);
}
bitmap.Dispose(); //release bitmap resources
if (exit)
Close(); //this should close the app, since this is the main form
}), null);
}
se puede ver por encima de la herramienta en acción en WebCapture (http://gallery.clipflair.net/WebCapture, código fuente en: http://ClipFlair.codeplex.com, ver carpeta Herramientas/WebCapture) que capte imágenes de los sitios web. Por cierto, si quieres llamar al ejecutable desde la línea de comandos asegúrate de ir a Propiedades del proyecto y en la pestaña Seguridad desactiva la seguridad ClickOnce (de lo contrario no puede acceder a la línea de comandos)
¿Eso es un sí o un no? ¿Y cómo funciona la interoperabilidad de WinForms en esto? –