Иногда компонент Timer полезен и прост в настройке в WinForms, просто установите его интервал и затем включите его, а затем убедитесь, что первое, что вы делаете в обработчике событий Tick, - это отключение самого себя.
Я думаю, что Timer запускает код в своем собственном потоке, поэтому вам все еще может потребоваться выполнить BeginInvoke (вызываемый объектом WinForm [this]) для запуска вашего действия.
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);
}
Вы можете увидеть выше в действии в инструменте WebCapture (http://gallery.clipflair.net/WebCapture, исходный код в: http://ClipFlair.codeplex.com, см. Папку Tools / WebCapture), которая захватывает скриншоты с веб-сайтов. Кстати, если вы хотите вызвать исполняемый файл из командной строки, убедитесь, что вы идете в Свойства проекта и на вкладке Безопасность отключите безопасность ClickOnce (иначе он не может получить доступ к командной строке)