简体   繁体   English

在窗体显示在屏幕上N秒后,如何编程代码以执行操作?

[英]How to program code to perform an action N seconds after the form is displayed on screen?

I'm writing a GUI application to display/graph a series of graphs. 我正在编写一个GUI应用程序以显示/绘制一系列图形。 When the application starts up it automatically reads the raw data from a specified location and automatically graphs and display them. 应用程序启动时,它将自动从指定位置读取原始数据,并自动绘制图形并显示它们。 I'm adding the capability to automatically save the graphs to file after they are displayed on screen. 我添加了在图形显示在屏幕上后自动将图形保存到文件的功能。

The way I'm doing the save is to grab the onscreen pixels into a bitmap and save the bitmap: 我执行保存的方法是将屏幕上的像素捕获到位图中并保存位图:

Bitmap memoryImage = new Bitmap(picCube.Size.Width, picCube.Size.Height);
Graphics g = Graphics.FromImage(memoryImage);
Point plotLoc = picBox.PointToScreen(Point.Empty);
g.CopyFromScreen(plotLoc.X, plotLoc.Y, 0, 0, picBox.Size);
memoryImage.Save(savePath, ImageFormat.Jpeg);

The restriction is this method only works after the graphs have already been displayed on screen. 限制是此方法仅在图形已经显示在屏幕上之后才起作用。 I have a menu item to do the save and it works without problem since the application has already been displayed on screen in order to get to the menu. 我有一个菜单项来进行保存,并且它可以正常工作,因为应用程序已经显示在屏幕上以便进入菜单。 Now that I'm adding an automatic save capability I need to be able to trigger this save action only AFTER the form has been fully displayed on screen. 现在,我添加了自动保存功能,仅在表单在屏幕上完全显示之后,才需要能够触发此保存操作。

I'm currently putting in a timer in the form's Load event that goes off in N seconds, which trigger the save action. 我目前在窗体的Load事件中放入一个计时器,该事件将在N秒后关闭,从而触发保存操作。 But for some reason it doesn't work, probably because the timer is in a different thread than the GUI thread which means the timer thread cannot access the GUI elements. 但是由于某些原因,它不起作用,可能是因为计时器与GUI线程不在同一线程中,这意味着计时器线程无法访问GUI元素。

Is there a better way to do this simple task without resorting to overly complicated approaches like background worker? 有没有更好的方法来完成此简单任务,而无需求助于背景工作人员等过于复杂的方法?

The form's Load is not the last even to fire when a form loads up. 表单Load ,表单的Load并不是最后一次触发。

Maybe try System.Windows.Forms.Form.Shown 也许尝试System.Windows.Forms.Form.Shown

Check out winforms event loading order: Winforms - order of Load and Activated events 查看winforms事件的加载顺序: Winforms-Load和Activated事件的顺序

That way you won't have to deal with issues where you depend on the local machine's timing. 这样,您将不必处理依赖本地计算机时间的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM