简体   繁体   中英

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. 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. 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.

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.

Maybe try System.Windows.Forms.Form.Shown

Check out winforms event loading order: Winforms - order of Load and Activated events

That way you won't have to deal with issues where you depend on the local machine's timing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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