I have a C# stand-alone (EXE) application, that does some data processing. At the end of the process, program takes a screenshot, saves the image (PNG) to a local folder and exits.
When I run this program locally, it works fine. The data processing is accomplished successfully, the screenshot is taken and the image is saved in the same folder with this EXE file.
Same goes for when I run this app manually on a remote Windows server. It works great.
However, the problem occurs, when this program runs as a scheduled task on a server. I setup a Windows Task Schedule to execute this program daily at certain time. But for the debugging purpose, I disabled all of the data processing code, only leaving code that takes the screenshot. In other words, the program opens a Console Window, prints some text using Console.WriteLine("Hello World"), takes the screenshot and goes into Console.ReadLine() awaiting user's input and then exits entirely. I scheduled this program to run one minute after I close the remote server.
This is where the problem occurs. For example, it is 10:00 AM now. I scheduled this program to run at 10:01 AM and closed the server by hitting "x" button. When I come back a couple of minutes later, I see Console Window opened with "Hello World" text and it's waiting for my input. I press key and program closes. But there is no screenshot image created.
Please see my code below:
static void Main(string[] args)
{
Console.WriteLine("Hello World");
string filename = Path.Combine(Application.StartupPath, "Screenshot.png");
ScreenCapture(filename);
Console.WriteLine("Press <ENTER> key to exit");
Console.ReadLine();
}
private static void ScreenCapture(string filename)
{
Rectangle res = Screen.PrimaryScreen.Bounds;
int screenLeft = res.Left;
int screenTop = res.Top;
int screenWidth = res.Width + 384;
int screenHeight = res.Height + 216;
try
{
using (Bitmap bitmap = new Bitmap(screenWidth, screenHeight))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(screenLeft, screenTop, 0, 0, bitmap.Size);
}
bitmap.Save(filename, ImageFormat.Png);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Source + "\n" + ex.Message + "\n" + ex.StackTrace);
}
}
Thank you in advance. I appreciate any help!
catchblock there? Very useful. Did you try to write to the Console the value ofApplication.StartupPath? Why are you using a WinForms property in a Console app?System.Drawing The handle is invalid at System.Drawing.Graphics.CopyFromScreen(Int32 sourceX, Int32 sourceY, Int32 destinationX, Int32 destinationY, Size blockRegionSize, CopyPixelOperation copyPixelOperation) at System.Drawing.Graphics.CopyFromScreen(Int32 sourceX, Int32 sourceY, Int32 destinationX, Int32 destinationY, Size blockRegionSize) at ScreenCapture.Program.ScreenCapture(String filename)